1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
|
/* Program for computing integer expressions using the GNU Multiple Precision
Arithmetic Library.
Copyright 1997, 1999-2002, 2005, 2008, 2012, 2015 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see https://www.gnu.org/licenses/. */
/* This expressions evaluator works by building an expression tree (using a
recursive descent parser) which is then evaluated. The expression tree is
useful since we want to optimize certain expressions (like a^b % c).
Usage: pexpr [options] expr ...
(Assuming you called the executable `pexpr' of course.)
Command line options:
-b print output in binary
-o print output in octal
-d print output in decimal (the default)
-x print output in hexadecimal
-b<NUM> print output in base NUM
-t print timing information
-html output html
-wml output wml
-split split long lines each 80th digit
*/
/* Define LIMIT_RESOURCE_USAGE if you want to make sure the program doesn't
use up extensive resources (cpu, memory). Useful for the GMP demo on the
GMP web site, since we cannot load the server too much. */
#include "pexpr-config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <signal.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/time.h>
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#include "gmp.h"
/* SunOS 4 and HPUX 9 don't define a canonical SIGSTKSZ, use a default. */
#ifndef SIGSTKSZ
#define SIGSTKSZ 4096
#endif
#define TIME(t,func) \
do { int __t0, __tmp; \
__t0 = cputime (); \
{func;} \
__tmp = cputime () - __t0; \
(t) = __tmp; \
} while (0)
/* GMP version 1.x compatibility. */
#if ! (__GNU_MP_VERSION >= 2)
typedef MP_INT __mpz_struct;
typedef __mpz_struct mpz_t[1];
typedef __mpz_struct *mpz_ptr;
#define mpz_fdiv_q mpz_div
#define mpz_fdiv_r mpz_mod
#define mpz_tdiv_q_2exp mpz_div_2exp
#define mpz_sgn(Z) ((Z)->size < 0 ? -1 : (Z)->size > 0)
#endif
/* GMP version 2.0 compatibility. */
#if ! (__GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1)
#define mpz_swap(a,b) \
do { __mpz_struct __t; __t = *a; *a = *b; *b = __t;} while (0)
#endif
jmp_buf errjmpbuf;
enum op_t {NOP, LIT, NEG, NOT, PLUS, MINUS, MULT, DIV, MOD, REM, INVMOD, POW,
AND, IOR, XOR, SLL, SRA, POPCNT, HAMDIST, GCD, LCM, SQRT, ROOT, FAC,
LOG, LOG2, FERMAT, MERSENNE, FIBONACCI, RANDOM, NEXTPRIME, BINOM,
TIMING};
/* Type for the expression tree. */
struct expr
{
enum op_t op;
union
{
struct {struct expr *lhs, *rhs;} ops;
mpz_t val;
} operands;
};
typedef struct expr *expr_t;
void cleanup_and_exit (int);
char *skipspace (char *);
void makeexp (expr_t *, enum op_t, expr_t, expr_t);
void free_expr (expr_t);
char *expr (char *, expr_t *);
char *term (char *, expr_t *);
char *power (char *, expr_t *);
char *factor (char *, expr_t *);
int match (char *, char *);
int matchp (char *, char *);
int cputime (void);
void mpz_eval_expr (mpz_ptr, expr_t);
void mpz_eval_mod_expr (mpz_ptr, expr_t, mpz_ptr);
char *error;
int flag_print = 1;
int print_timing = 0;
int flag_html = 0;
int flag_wml = 0;
int flag_splitup_output = 0;
char *newline = "";
gmp_randstate_t rstate;
/* cputime() returns user CPU time measured in milliseconds. */
#if ! HAVE_CPUTIME
#if HAVE_GETRUSAGE
int
cputime (void)
{
struct rusage rus;
getrusage (0, &rus);
return rus.ru_utime.tv_sec * 1000 + rus.ru_utime.tv_usec / 1000;
}
#else
#if HAVE_CLOCK
int
cputime (void)
{
if (CLOCKS_PER_SEC < 100000)
return clock () * 1000 / CLOCKS_PER_SEC;
return clock () / (CLOCKS_PER_SEC / 1000);
}
#else
int
cputime (void)
{
return 0;
}
#endif
#endif
#endif
int
stack_downwards_helper (char *xp)
{
char y;
return &y < xp;
}
int
stack_downwards_p (void)
{
char x;
return stack_downwards_helper (&x);
}
void
setup_error_handler (void)
{
#if HAVE_SIGACTION
struct sigaction act;
act.sa_handler = cleanup_and_exit;
sigemptyset (&(act.sa_mask));
#define SIGNAL(sig) sigaction (sig, &act, NULL)
#else
struct { int sa_flags; } act;
#define SIGNAL(sig) signal (sig, cleanup_and_exit)
#endif
act.sa_flags = 0;
/* Set up a stack for signal handling. A typical cause of error is stack
overflow, and in such situation a signal can not be delivered on the
overflown stack. */
#if HAVE_SIGALTSTACK
{
/* AIX uses stack_t, MacOS uses struct sigaltstack, various other
systems have both. */
#if HAVE_STACK_T
stack_t s;
#else
struct sigaltstack s;
#endif
s.ss_sp = malloc (SIGSTKSZ);
s.ss_size = SIGSTKSZ;
s.ss_flags = 0;
if (sigaltstack (&s, NULL) != 0)
perror("sigaltstack");
act.sa_flags = SA_ONSTACK;
}
#else
#if HAVE_SIGSTACK
{
struct sigstack s;
s.ss_sp = malloc (SIGSTKSZ);
if (stack_downwards_p ())
s.ss_sp += SIGSTKSZ;
s.ss_onstack = 0;
if (sigstack (&s, NULL) != 0)
perror("sigstack");
act.sa_flags = SA_ONSTACK;
}
#else
#endif
#endif
#ifdef LIMIT_RESOURCE_USAGE
{
struct rlimit limit;
limit.rlim_cur = limit.rlim_max = 0;
setrlimit (RLIMIT_CORE, &limit);
limit.rlim_cur = 3;
limit.rlim_max = 4;
setrlimit (RLIMIT_CPU, &limit);
limit.rlim_cur = limit.rlim_max = 16 * 1024 * 1024;
setrlimit (RLIMIT_DATA, &limit);
getrlimit (RLIMIT_STACK, &limit);
limit.rlim_cur = 4 * 1024 * 1024;
setrlimit (RLIMIT_STACK, &limit);
SIGNAL (SIGXCPU);
}
#endif /* LIMIT_RESOURCE_USAGE */
SIGNAL (SIGILL);
SIGNAL (SIGSEGV);
#ifdef SIGBUS /* not in mingw */
SIGNAL (SIGBUS);
#endif
SIGNAL (SIGFPE);
SIGNAL (SIGABRT);
}
int
main (int argc, char **argv)
{
struct expr *e;
int i;
mpz_t r;
int errcode = 0;
char *str;
int base = 10;
setup_error_handler ();
gmp_randinit (rstate, GMP_RAND_ALG_LC, 128);
{
#if HAVE_GETTIMEOFDAY
struct timeval tv;
gettimeofday (&tv, NULL);
gmp_randseed_ui (rstate, tv.tv_sec + tv.tv_usec);
#else
time_t t;
time (&t);
gmp_randseed_ui (rstate, t);
#endif
}
mpz_init (r);
while (argc > 1 && argv[1][0] == '-')
{
char *arg = argv[1];
if (arg[1] >= '0' && arg[1] <= '9')
break;
if (arg[1] == 't')
print_timing = 1;
else if (arg[1] == 'b' && arg[2] >= '0' && arg[2] <= '9')
{
base = atoi (arg + 2);
if (base < 2 || base > 62)
{
fprintf (stderr, "error: invalid output base\n");
exit (-1);
}
}
else if (arg[1] == 'b' && arg[2] == 0)
base = 2;
else if (arg[1] == 'x' && arg[2] == 0)
base = 16;
else if (arg[1] == 'X' && arg[2] == 0)
base = -16;
else if (arg[1] == 'o' && arg[2] == 0)
base = 8;
else if (arg[1] == 'd' && arg[2] == 0)
base = 10;
else if (arg[1] == 'v' && arg[2] == 0)
{
printf ("pexpr linked to gmp %s\n", __gmp_version);
}
else if (strcmp (arg, "-html") == 0)
{
flag_html = 1;
newline = "<br>";
}
else if (strcmp (arg, "-wml") == 0)
{
flag_wml = 1;
newline = "<br/>";
}
else if (strcmp (arg, "-split") == 0)
{
flag_splitup_output = 1;
}
else if (strcmp (arg, "-noprint") == 0)
{
flag_print = 0;
}
else
{
fprintf (stderr, "error: unknown option `%s'\n", arg);
exit (-1);
}
argv++;
argc--;
}
for (i = 1; i < argc; i++)
{
int s;
int jmpval;
/* Set up error handler for parsing expression. */
jmpval = setjmp (errjmpbuf);
if (jmpval != 0)
{
fprintf (stderr, "error: %s%s\n", error, newline);
fprintf (stderr, " %s%s\n", argv[i], newline);
if (! flag_html)
{
/* ??? Dunno how to align expression position with arrow in
HTML ??? */
fprintf (stderr, " ");
for (s = jmpval - (long) argv[i]; --s >= 0; )
putc (' ', stderr);
fprintf (stderr, "^\n");
}
errcode |= 1;
continue;
}
str = expr (argv[i], &e);
if (str[0] != 0)
{
fprintf (stderr,
"error: garbage where end of expression expected%s\n",
newline);
fprintf (stderr, " %s%s\n", argv[i], newline);
if (! flag_html)
{
/* ??? Dunno how to align expression position with arrow in
HTML ??? */
fprintf (stderr, " ");
for (s = str - argv[i]; --s; )
putc (' ', stderr);
fprintf (stderr, "^\n");
}
errcode |= 1;
free_expr (e);
continue;
}
/* Set up error handler for evaluating expression. */
if (setjmp (errjmpbuf))
{
fprintf (stderr, "error: %s%s\n", error, newline);
fprintf (stderr, " %s%s\n", argv[i], newline);
if (! flag_html)
{
/* ??? Dunno how to align expression position with arrow in
HTML ??? */
fprintf (stderr, " ");
for (s = str - argv[i]; --s >= 0; )
putc (' ', stderr);
fprintf (stderr, "^\n");
}
errcode |= 2;
continue;
}
if (print_timing)
{
int t;
TIME (t, mpz_eval_expr (r, e));
printf ("computation took %d ms%s\n", t, newline);
}
else
mpz_eval_expr (r, e);
if (flag_print)
{
size_t out_len;
char *tmp, *s;
out_len = mpz_sizeinbase (r, base >= 0 ? base : -base) + 2;
#ifdef LIMIT_RESOURCE_USAGE
if (out_len > 100000)
{
printf ("result is about %ld digits, not printing it%s\n",
(long) out_len - 3, newline);
exit (-2);
}
#endif
tmp = malloc (out_len);
if (print_timing)
{
int t;
printf ("output conversion ");
TIME (t, mpz_get_str (tmp, base, r));
printf ("took %d ms%s\n", t, newline);
}
else
mpz_get_str (tmp, base, r);
out_len = strlen (tmp);
if (flag_splitup_output)
{
for (s = tmp; out_len > 80; s += 80)
{
fwrite (s, 1, 80, stdout);
printf ("%s\n", newline);
out_len -= 80;
}
fwrite (s, 1, out_len, stdout);
}
else
{
fwrite (tmp, 1, out_len, stdout);
}
free (tmp);
printf ("%s\n", newline);
}
else
{
printf ("result is approximately %ld digits%s\n",
(long) mpz_sizeinbase (r, base >= 0 ? base : -base),
newline);
}
free_expr (e);
}
mpz_clear (r);
exit (errcode);
}
char *
expr (char *str, expr_t *e)
{
expr_t e2;
str = skipspace (str);
if (str[0] == '+')
{
str = term (str + 1, e);
}
else if (str[0] == '-')
{
str = term (str + 1, e);
makeexp (e, NEG, *e, NULL);
}
else if (str[0] == '~')
{
str = term (str + 1, e);
makeexp (e, NOT, *e, NULL);
}
else
{
str = term (str, e);
}
for (;;)
{
str = skipspace (str);
switch (str[0])
{
case 'p':
if (match ("plus", str))
{
str = term (str + 4, &e2);
makeexp (e, PLUS, *e, e2);
}
else
return str;
break;
case 'm':
if (match ("minus", str))
{
str = term (str + 5, &e2);
makeexp (e, MINUS, *e, e2);
}
else
return str;
break;
case '+':
str = term (str + 1, &e2);
makeexp (e, PLUS, *e, e2);
break;
case '-':
str = term (str + 1, &e2);
makeexp (e, MINUS, *e, e2);
break;
default:
return str;
}
}
}
char *
term (char *str, expr_t *e)
{
expr_t e2;
str = power (str, e);
for (;;)
{
str = skipspace (str);
switch (str[0])
{
case 'm':
if (match ("mul", str))
{
str = power (str + 3, &e2);
makeexp (e, MULT, *e, e2);
break;
}
if (match ("mod", str))
{
str = power (str + 3, &e2);
makeexp (e, MOD, *e, e2);
break;
}
return str;
case 'd':
if (match ("div", str))
{
str = power (str + 3, &e2);
makeexp (e, DIV, *e, e2);
break;
}
return str;
case 'r':
if (match ("rem", str))
{
str = power (str + 3, &e2);
makeexp (e, REM, *e, e2);
break;
}
return str;
case 'i':
if (match ("invmod", str))
{
str = power (str + 6, &e2);
makeexp (e, REM, *e, e2);
break;
}
return str;
case 't':
if (match ("times", str))
{
str = power (str + 5, &e2);
makeexp (e, MULT, *e, e2);
break;
}
if (match ("thru", str))
{
str = power (str + 4, &e2);
makeexp (e, DIV, *e, e2);
break;
}
if (match ("through", str))
{
str = power (str + 7, &e2);
makeexp (e, DIV, *e, e2);
break;
}
return str;
case '*':
str = power (str + 1, &e2);
makeexp (e, MULT, *e, e2);
break;
case '/':
str = power (str + 1, &e2);
makeexp (e, DIV, *e, e2);
break;
case '%':
str = power (str + 1, &e2);
makeexp (e, MOD, *e, e2);
break;
default:
return str;
}
}
}
char *
power (char *str, expr_t *e)
{
expr_t e2;
str = factor (str, e);
while (str[0] == '!')
{
str++;
makeexp (e, FAC, *e, NULL);
}
str = skipspace (str);
if (str[0] == '^')
{
str = power (str + 1, &e2);
makeexp (e, POW, *e, e2);
}
return str;
}
int
match (char *s, char *str)
{
char *ostr = str;
int i;
for (i = 0; s[i] != 0; i++)
{
if (str[i] != s[i])
return 0;
}
str = skipspace (str + i);
return str - ostr;
}
int
matchp (char *s, char *str)
{
char *ostr = str;
int i;
for (i = 0; s[i] != 0; i++)
{
if (str[i] != s[i])
return 0;
}
str = skipspace (str + i);
if (str[0] == '(')
return str - ostr + 1;
return 0;
}
struct functions
{
char *spelling;
enum op_t op;
int arity; /* 1 or 2 means real arity; 0 means arbitrary. */
};
struct functions fns[] =
{
{"sqrt", SQRT, 1},
#if __GNU_MP_VERSION >= 2
{"root", ROOT, 2},
{"popc", POPCNT, 1},
{"hamdist", HAMDIST, 2},
#endif
{"gcd", GCD, 0},
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
{"lcm", LCM, 0},
#endif
{"and", AND, 0},
{"ior", IOR, 0},
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
{"xor", XOR, 0},
#endif
{"plus", PLUS, 0},
{"pow", POW, 2},
{"minus", MINUS, 2},
{"mul", MULT, 0},
{"div", DIV, 2},
{"mod", MOD, 2},
{"rem", REM, 2},
#if __GNU_MP_VERSION >= 2
{"invmod", INVMOD, 2},
#endif
{"log", LOG, 2},
{"log2", LOG2, 1},
{"F", FERMAT, 1},
{"M", MERSENNE, 1},
{"fib", FIBONACCI, 1},
{"Fib", FIBONACCI, 1},
{"random", RANDOM, 1},
{"nextprime", NEXTPRIME, 1},
{"binom", BINOM, 2},
{"binomial", BINOM, 2},
{"fac", FAC, 1},
{"fact", FAC, 1},
{"factorial", FAC, 1},
{"time", TIMING, 1},
{"", NOP, 0}
};
char *
factor (char *str, expr_t *e)
{
expr_t e1, e2;
str = skipspace (str);
if (isalpha (str[0]))
{
int i;
int cnt;
for (i = 0; fns[i].op != NOP; i++)
{
if (fns[i].arity == 1)
{
cnt = matchp (fns[i].spelling, str);
if (cnt != 0)
{
str = expr (str + cnt, &e1);
str = skipspace (str);
if (str[0] != ')')
{
error = "expected `)'";
longjmp (errjmpbuf, (int) (long) str);
}
makeexp (e, fns[i].op, e1, NULL);
return str + 1;
}
}
}
for (i = 0; fns[i].op != NOP; i++)
{
if (fns[i].arity != 1)
{
cnt = matchp (fns[i].spelling, str);
if (cnt != 0)
{
str = expr (str + cnt, &e1);
str = skipspace (str);
if (str[0] != ',')
{
error = "expected `,' and another operand";
longjmp (errjmpbuf, (int) (long) str);
}
str = skipspace (str + 1);
str = expr (str, &e2);
str = skipspace (str);
if (fns[i].arity == 0)
{
while (str[0] == ',')
{
makeexp (&e1, fns[i].op, e1, e2);
str = skipspace (str + 1);
str = expr (str, &e2);
str = skipspace (str);
}
}
if (str[0] != ')')
{
error = "expected `)'";
longjmp (errjmpbuf, (int) (long) str);
}
makeexp (e, fns[i].op, e1, e2);
return str + 1;
}
}
}
}
if (str[0] == '(')
{
str = expr (str + 1, e);
str = skipspace (str);
if (str[0] != ')')
{
error = "expected `)'";
longjmp (errjmpbuf, (int) (long) str);
}
str++;
}
else if (str[0] >= '0' && str[0] <= '9')
{
expr_t res;
char *s, *sc;
res = malloc (sizeof (struct expr));
res -> op = LIT;
mpz_init (res->operands.val);
s = str;
while (isalnum (str[0]))
str++;
sc = malloc (str - s + 1);
memcpy (sc, s, str - s);
sc[str - s] = 0;
mpz_set_str (res->operands.val, sc, 0);
*e = res;
free (sc);
}
else
{
error = "operand expected";
longjmp (errjmpbuf, (int) (long) str);
}
return str;
}
char *
skipspace (char *str)
{
while (str[0] == ' ')
str++;
return str;
}
/* Make a new expression with operation OP and right hand side
RHS and left hand side lhs. Put the result in R. */
void
makeexp (expr_t *r, enum op_t op, expr_t lhs, expr_t rhs)
{
expr_t res;
res = malloc (sizeof (struct expr));
res -> op = op;
res -> operands.ops.lhs = lhs;
res -> operands.ops.rhs = rhs;
*r = res;
return;
}
/* Free the memory used by expression E. */
void
free_expr (expr_t e)
{
if (e->op != LIT)
{
free_expr (e->operands.ops.lhs);
if (e->operands.ops.rhs != NULL)
free_expr (e->operands.ops.rhs);
}
else
{
mpz_clear (e->operands.val);
}
}
/* Evaluate the expression E and put the result in R. */
void
mpz_eval_expr (mpz_ptr r, expr_t e)
{
mpz_t lhs, rhs;
switch (e->op)
{
case LIT:
mpz_set (r, e->operands.val);
return;
case PLUS:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_add (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
case MINUS:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_sub (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
case MULT:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_mul (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
case DIV:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_fdiv_q (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
case MOD:
mpz_init (rhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_abs (rhs, rhs);
mpz_eval_mod_expr (r, e->operands.ops.lhs, rhs);
mpz_clear (rhs);
return;
case REM:
/* Check if lhs operand is POW expression and optimize for that case. */
if (e->operands.ops.lhs->op == POW)
{
mpz_t powlhs, powrhs;
mpz_init (powlhs);
mpz_init (powrhs);
mpz_init (rhs);
mpz_eval_expr (powlhs, e->operands.ops.lhs->operands.ops.lhs);
mpz_eval_expr (powrhs, e->operands.ops.lhs->operands.ops.rhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_powm (r, powlhs, powrhs, rhs);
if (mpz_cmp_si (rhs, 0L) < 0)
mpz_neg (r, r);
mpz_clear (powlhs);
mpz_clear (powrhs);
mpz_clear (rhs);
return;
}
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_fdiv_r (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#if __GNU_MP_VERSION >= 2
case INVMOD:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_invert (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#endif
case POW:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
if (mpz_cmpabs_ui (lhs, 1) <= 0)
{
/* For 0^rhs and 1^rhs, we just need to verify that
rhs is well-defined. For (-1)^rhs we need to
determine (rhs mod 2). For simplicity, compute
(rhs mod 2) for all three cases. */
expr_t two, et;
two = malloc (sizeof (struct expr));
two -> op = LIT;
mpz_init_set_ui (two->operands.val, 2L);
makeexp (&et, MOD, e->operands.ops.rhs, two);
e->operands.ops.rhs = et;
}
mpz_eval_expr (rhs, e->operands.ops.rhs);
if (mpz_cmp_si (rhs, 0L) == 0)
/* x^0 is 1 */
mpz_set_ui (r, 1L);
else if (mpz_cmp_si (lhs, 0L) == 0)
/* 0^y (where y != 0) is 0 */
mpz_set_ui (r, 0L);
else if (mpz_cmp_ui (lhs, 1L) == 0)
/* 1^y is 1 */
mpz_set_ui (r, 1L);
else if (mpz_cmp_si (lhs, -1L) == 0)
/* (-1)^y just depends on whether y is even or odd */
mpz_set_si (r, (mpz_get_ui (rhs) & 1) ? -1L : 1L);
else if (mpz_cmp_si (rhs, 0L) < 0)
/* x^(-n) is 0 */
mpz_set_ui (r, 0L);
else
{
unsigned long int cnt;
unsigned long int y;
/* error if exponent does not fit into an unsigned long int. */
if (mpz_cmp_ui (rhs, ~(unsigned long int) 0) > 0)
goto pow_err;
y = mpz_get_ui (rhs);
/* x^y == (x/(2^c))^y * 2^(c*y) */
#if __GNU_MP_VERSION >= 2
cnt = mpz_scan1 (lhs, 0);
#else
cnt = 0;
#endif
if (cnt != 0)
{
if (y * cnt / cnt != y)
goto pow_err;
mpz_tdiv_q_2exp (lhs, lhs, cnt);
mpz_pow_ui (r, lhs, y);
mpz_mul_2exp (r, r, y * cnt);
}
else
mpz_pow_ui (r, lhs, y);
}
mpz_clear (lhs); mpz_clear (rhs);
return;
pow_err:
error = "result of `pow' operator too large";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
case GCD:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_gcd (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
case LCM:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_lcm (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#endif
case AND:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_and (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
case IOR:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_ior (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
case XOR:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_xor (r, lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
return;
#endif
case NEG:
mpz_eval_expr (r, e->operands.ops.lhs);
mpz_neg (r, r);
return;
case NOT:
mpz_eval_expr (r, e->operands.ops.lhs);
mpz_com (r, r);
return;
case SQRT:
mpz_init (lhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
if (mpz_sgn (lhs) < 0)
{
error = "cannot take square root of negative numbers";
mpz_clear (lhs);
longjmp (errjmpbuf, 1);
}
mpz_sqrt (r, lhs);
return;
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
case ROOT:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
if (mpz_sgn (rhs) <= 0)
{
error = "cannot take non-positive root orders";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
}
if (mpz_sgn (lhs) < 0 && (mpz_get_ui (rhs) & 1) == 0)
{
error = "cannot take even root orders of negative numbers";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
}
{
unsigned long int nth = mpz_get_ui (rhs);
if (mpz_cmp_ui (rhs, ~(unsigned long int) 0) > 0)
{
/* If we are asked to take an awfully large root order, cheat and
ask for the largest order we can pass to mpz_root. This saves
some error prone special cases. */
nth = ~(unsigned long int) 0;
}
mpz_root (r, lhs, nth);
}
mpz_clear (lhs); mpz_clear (rhs);
return;
#endif
case FAC:
mpz_eval_expr (r, e->operands.ops.lhs);
if (mpz_size (r) > 1)
{
error = "result of `!' operator too large";
longjmp (errjmpbuf, 1);
}
mpz_fac_ui (r, mpz_get_ui (r));
return;
#if __GNU_MP_VERSION >= 2
case POPCNT:
mpz_eval_expr (r, e->operands.ops.lhs);
{ long int cnt;
cnt = mpz_popcount (r);
mpz_set_si (r, cnt);
}
return;
case HAMDIST:
{ long int cnt;
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
cnt = mpz_hamdist (lhs, rhs);
mpz_clear (lhs); mpz_clear (rhs);
mpz_set_si (r, cnt);
}
return;
#endif
case LOG2:
mpz_eval_expr (r, e->operands.ops.lhs);
{ unsigned long int cnt;
if (mpz_sgn (r) <= 0)
{
error = "logarithm of non-positive number";
longjmp (errjmpbuf, 1);
}
cnt = mpz_sizeinbase (r, 2);
mpz_set_ui (r, cnt - 1);
}
return;
case LOG:
{ unsigned long int cnt;
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
if (mpz_sgn (lhs) <= 0)
{
error = "logarithm of non-positive number";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
}
if (mpz_cmp_ui (rhs, 256) >= 0)
{
error = "logarithm base too large";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
}
cnt = mpz_sizeinbase (lhs, mpz_get_ui (rhs));
mpz_set_ui (r, cnt - 1);
mpz_clear (lhs); mpz_clear (rhs);
}
return;
case FERMAT:
{
unsigned long int t;
mpz_init (lhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
t = (unsigned long int) 1 << mpz_get_ui (lhs);
if (mpz_cmp_ui (lhs, ~(unsigned long int) 0) > 0 || t == 0)
{
error = "too large Mersenne number index";
mpz_clear (lhs);
longjmp (errjmpbuf, 1);
}
mpz_set_ui (r, 1);
mpz_mul_2exp (r, r, t);
mpz_add_ui (r, r, 1);
mpz_clear (lhs);
}
return;
case MERSENNE:
mpz_init (lhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
if (mpz_cmp_ui (lhs, ~(unsigned long int) 0) > 0)
{
error = "too large Mersenne number index";
mpz_clear (lhs);
longjmp (errjmpbuf, 1);
}
mpz_set_ui (r, 1);
mpz_mul_2exp (r, r, mpz_get_ui (lhs));
mpz_sub_ui (r, r, 1);
mpz_clear (lhs);
return;
case FIBONACCI:
{ mpz_t t;
unsigned long int n, i;
mpz_init (lhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
if (mpz_sgn (lhs) <= 0 || mpz_cmp_si (lhs, 1000000000) > 0)
{
error = "Fibonacci index out of range";
mpz_clear (lhs);
longjmp (errjmpbuf, 1);
}
n = mpz_get_ui (lhs);
mpz_clear (lhs);
#if __GNU_MP_VERSION > 2 || __GNU_MP_VERSION_MINOR >= 1
mpz_fib_ui (r, n);
#else
mpz_init_set_ui (t, 1);
mpz_set_ui (r, 1);
if (n <= 2)
mpz_set_ui (r, 1);
else
{
for (i = 3; i <= n; i++)
{
mpz_add (t, t, r);
mpz_swap (t, r);
}
}
mpz_clear (t);
#endif
}
return;
case RANDOM:
{
unsigned long int n;
mpz_init (lhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
if (mpz_sgn (lhs) <= 0 || mpz_cmp_si (lhs, 1000000000) > 0)
{
error = "random number size out of range";
mpz_clear (lhs);
longjmp (errjmpbuf, 1);
}
n = mpz_get_ui (lhs);
mpz_clear (lhs);
mpz_urandomb (r, rstate, n);
}
return;
case NEXTPRIME:
{
mpz_eval_expr (r, e->operands.ops.lhs);
mpz_nextprime (r, r);
}
return;
case BINOM:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_expr (lhs, e->operands.ops.lhs);
mpz_eval_expr (rhs, e->operands.ops.rhs);
{
unsigned long int k;
if (mpz_cmp_ui (rhs, ~(unsigned long int) 0) > 0)
{
error = "k too large in (n over k) expression";
mpz_clear (lhs); mpz_clear (rhs);
longjmp (errjmpbuf, 1);
}
k = mpz_get_ui (rhs);
mpz_bin_ui (r, lhs, k);
}
mpz_clear (lhs); mpz_clear (rhs);
return;
case TIMING:
{
int t0;
t0 = cputime ();
mpz_eval_expr (r, e->operands.ops.lhs);
printf ("time: %d\n", cputime () - t0);
}
return;
default:
abort ();
}
}
/* Evaluate the expression E modulo MOD and put the result in R. */
void
mpz_eval_mod_expr (mpz_ptr r, expr_t e, mpz_ptr mod)
{
mpz_t lhs, rhs;
switch (e->op)
{
case POW:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_mod_expr (lhs, e->operands.ops.lhs, mod);
mpz_eval_expr (rhs, e->operands.ops.rhs);
mpz_powm (r, lhs, rhs, mod);
mpz_clear (lhs); mpz_clear (rhs);
return;
case PLUS:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_mod_expr (lhs, e->operands.ops.lhs, mod);
mpz_eval_mod_expr (rhs, e->operands.ops.rhs, mod);
mpz_add (r, lhs, rhs);
if (mpz_cmp_si (r, 0L) < 0)
mpz_add (r, r, mod);
else if (mpz_cmp (r, mod) >= 0)
mpz_sub (r, r, mod);
mpz_clear (lhs); mpz_clear (rhs);
return;
case MINUS:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_mod_expr (lhs, e->operands.ops.lhs, mod);
mpz_eval_mod_expr (rhs, e->operands.ops.rhs, mod);
mpz_sub (r, lhs, rhs);
if (mpz_cmp_si (r, 0L) < 0)
mpz_add (r, r, mod);
else if (mpz_cmp (r, mod) >= 0)
mpz_sub (r, r, mod);
mpz_clear (lhs); mpz_clear (rhs);
return;
case MULT:
mpz_init (lhs); mpz_init (rhs);
mpz_eval_mod_expr (lhs, e->operands.ops.lhs, mod);
mpz_eval_mod_expr (rhs, e->operands.ops.rhs, mod);
mpz_mul (r, lhs, rhs);
mpz_mod (r, r, mod);
mpz_clear (lhs); mpz_clear (rhs);
return;
default:
mpz_init (lhs);
mpz_eval_expr (lhs, e);
mpz_mod (r, lhs, mod);
mpz_clear (lhs);
return;
}
}
void
cleanup_and_exit (int sig)
{
switch (sig) {
#ifdef LIMIT_RESOURCE_USAGE
case SIGXCPU:
printf ("expression took too long to evaluate%s\n", newline);
break;
#endif
case SIGFPE:
printf ("divide by zero%s\n", newline);
break;
default:
printf ("expression required too much memory to evaluate%s\n", newline);
break;
}
exit (-2);
}
|