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
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
|
/***********************************************************
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
/* MPZ module */
/* This module provides an interface to an alternate Multi-Precision
library, GNU MP in this case */
/* XXX note: everywhere where mpz_size is called,
sizeof (limb) == sizeof (long) has been assumed. */
/* MPZ objects */
#include "allobjects.h"
#include <assert.h>
#include <sys/types.h> /* For size_t */
/*
** These are the cpp-flags used in this file...
**
**
** MPZ_MDIV_BUG works around the mpz_m{div,mod,...} routines.
** This bug has been fixed in a later release of
** GMP.
**
** MPZ_GET_STR_BUG mpz_get_str corrupts memory, seems to be fixed
** in a later release
**
** MPZ_DEBUG generates a bunch of diagnostic messages
**
** MPZ_SPARE_MALLOC if set, results in extra code that tries to
** minimize the creation of extra objects.
**
** MPZ_TEST_DIV extra diagnostic output on stderr, when division
** routines are involved
**
** MPZ_LIB_DOES_CHECKING if set, assumes that mpz library doesn't call
** alloca with arg < 0 (when casted to a signed
** integral type).
**
** MPZ_CONVERSIONS_AS_METHODS if set, presents the conversions as
** methods. e.g., `mpz(5).long() == 5L'
** Later, Guido provided an interface to the
** standard functions. So this flag has no been
** cleared, and `long(mpz(5)) == 5L'
**
** MP_TEST_ALLOC If set, you would discover why MPZ_GET_STR_BUG
** is needed
**
** MAKEDUMMYINT Must be set if dynamic linking will be used
*/
/*
** IMHO, mpz_m{div,mod,divmod}() do the wrong things when the denominator < 0
** I assume that this will be fixed in a future release
*/
/*#define MPZ_MDIV_BUG fixed the (for me) nexessary parts in libgmp.a */
/*
** IMO, mpz_get_str() assumes a bit too large target space, if he doesn't
** allocate it himself
*/
#define MPZ_GET_STR_BUG
#include "gmp.h"
typedef struct {
OB_HEAD
MP_INT mpz; /* the actual number */
} mpzobject;
staticforward typeobject MPZtype;
#define is_mpzobject(v) ((v)->ob_type == &MPZtype)
static const char initialiser_name[] = "mpz";
/* #define MPZ_DEBUG */
static mpzobject *
newmpzobject()
{
mpzobject *mpzp;
#ifdef MPZ_DEBUG
fputs( "mpz_object() called...\n", stderr );
#endif /* def MPZ_DEBUG */
mpzp = NEWOBJ(mpzobject, &MPZtype);
if (mpzp == NULL)
return NULL;
mpz_init(&mpzp->mpz); /* actual initialisation */
return mpzp;
} /* newmpzobject() */
#ifdef MPZ_GET_STR_BUG
#include "gmp-impl.h"
#include "longlong.h"
#endif /* def MPZ_GET_STR_BUG */
static object *
mpz_format(objp, base, withname)
object *objp;
int base;
unsigned char withname;
{
mpzobject *mpzp = (mpzobject *)objp;
stringobject *strobjp;
int i;
int cmpres;
int taglong;
char *cp;
char prefix[5], *tcp;
tcp = &prefix[0];
if (mpzp == NULL || !is_mpzobject(mpzp)) {
err_badcall();
return NULL;
}
assert(base >= 2 && base <= 36);
if (withname)
i = strlen(initialiser_name) + 2; /* e.g. 'mpz(' + ')' */
else
i = 0;
if ((cmpres = mpz_cmp_si(&mpzp->mpz, 0L)) == 0)
base = 10; /* '0' in every base, right */
else if (cmpres < 0) {
*tcp++ = '-';
i += 1; /* space to hold '-' */
}
#ifdef MPZ_DEBUG
fprintf(stderr, "mpz_format: mpz_sizeinbase %d\n",
(int)mpz_sizeinbase(&mpzp->mpz, base));
#endif /* def MPZ_DEBUG */
#ifdef MPZ_GET_STR_BUG
i += ((size_t) abs(mpzp->mpz.size) * BITS_PER_MP_LIMB
* __mp_bases[base].chars_per_bit_exactly) + 1;
#else /* def MPZ_GET_STR_BUG */
i += (int)mpz_sizeinbase(&mpzp->mpz, base);
#endif /* def MPZ_GET_STR_BUG else */
if (base == 16) {
*tcp++ = '0';
*tcp++ = 'x';
i += 2; /* space to hold '0x' */
}
else if (base == 8) {
*tcp++ = '0';
i += 1; /* space to hold the extra '0' */
}
else if (base > 10) {
*tcp++ = '0' + base / 10;
*tcp++ = '0' + base % 10;
*tcp++ = '#';
i += 3; /* space to hold e.g. '12#' */
}
else if (base < 10) {
*tcp++ = '0' + base;
*tcp++ = '#';
i += 2; /* space to hold e.g. '6#' */
}
/*
** the following code looks if we need a 'L' attached to the number
** it will also attach an 'L' to the value -0x80000000
*/
taglong = 0;
if (mpz_size(&mpzp->mpz) > 1
|| (long)mpz_get_ui(&mpzp->mpz) < 0L) {
taglong = 1;
i += 1; /* space to hold 'L' */
}
#ifdef MPZ_DEBUG
fprintf(stderr, "mpz_format: requesting string size %d\n", i);
#endif /* def MPZ_DEBUG */
if ((strobjp = (stringobject *)newsizedstringobject((char *)0, i))
== NULL)
return NULL;
/* get the beginning of the string memory and start copying things */
cp = GETSTRINGVALUE(strobjp);
if (withname) {
strcpy(cp, initialiser_name);
cp += strlen(initialiser_name);
*cp++ = '('; /*')'*/
}
/* copy the already prepared prefix; e.g. sign and base indicator */
*tcp = '\0';
strcpy(cp, prefix);
cp += tcp - prefix;
/* since' we have the sign already, let the lib think it's a positive
number */
if (cmpres < 0)
mpz_neg(&mpzp->mpz,&mpzp->mpz); /* hack Hack HAck HACk HACK */
(void)mpz_get_str(cp, base, &mpzp->mpz);
if (cmpres < 0)
mpz_neg(&mpzp->mpz,&mpzp->mpz); /* hack Hack HAck HACk HACK */
#ifdef MPZ_DEBUG
fprintf(stderr, "mpz_format: base (ultim) %d, mpz_get_str: %s\n",
base, cp);
#endif /* def MPZ_DEBUG */
cp += strlen(cp);
if (taglong)
*cp++ = 'L';
if (withname)
*cp++ = /*'('*/ ')';
*cp = '\0';
#ifdef MPZ_DEBUG
fprintf(stderr,
"mpz_format: cp (str end) 0x%x, begin 0x%x, diff %d, i %d\n",
cp, GETSTRINGVALUE(strobjp), cp - GETSTRINGVALUE(strobjp), i);
#endif /* def MPZ_DEBUG */
assert(cp - GETSTRINGVALUE(strobjp) <= i);
if (cp - GETSTRINGVALUE(strobjp) != i) {
strobjp->ob_size -= i - (cp - GETSTRINGVALUE(strobjp));
}
return (object *)strobjp;
} /* mpz_format() */
/* MPZ methods */
static void
mpz_dealloc(mpzp)
mpzobject *mpzp;
{
#ifdef MPZ_DEBUG
fputs( "mpz_dealloc() called...\n", stderr );
#endif /* def MPZ_DEBUG */
mpz_clear(&mpzp->mpz);
DEL(mpzp);
} /* mpz_dealloc() */
/* pointers to frequently used values 0, 1 and -1 */
static mpzobject *mpz_value_zero, *mpz_value_one, *mpz_value_mone;
static int
mpz_compare(a, b)
mpzobject *a, *b;
{
int cmpres;
/* guido sez it's better to return -1, 0 or 1 */
return (cmpres = mpz_cmp( &a->mpz, &b->mpz )) == 0 ? 0
: cmpres > 0 ? 1 : -1;
} /* mpz_compare() */
static object *
mpz_addition(a, b)
mpzobject *a;
mpzobject *b;
{
mpzobject *z;
#ifdef MPZ_SPARE_MALLOC
if (mpz_cmp_ui(&a->mpz, (unsigned long int)0) == 0) {
INCREF(b);
return (object *)b;
}
if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) {
INCREF(a);
return (object *)a;
}
#endif /* def MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_add(&z->mpz, &a->mpz, &b->mpz);
return (object *)z;
} /* mpz_addition() */
static object *
mpz_substract(a, b)
mpzobject *a;
mpzobject *b;
{
mpzobject *z;
#ifdef MPZ_SPARE_MALLOC
if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) {
INCREF(a);
return (object *)a;
}
#endif /* MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_sub(&z->mpz, &a->mpz, &b->mpz);
return (object *)z;
} /* mpz_substract() */
static object *
mpz_multiply(a, b)
mpzobject *a;
mpzobject *b;
{
#ifdef MPZ_SPARE_MALLOC
int cmpres;
#endif /* def MPZ_SPARE_MALLOC */
mpzobject *z;
#ifdef MPZ_SPARE_MALLOC
if ((cmpres = mpz_cmp_ui(&a->mpz, (unsigned long int)0)) == 0) {
INCREF(mpz_value_zero);
return (object *)mpz_value_zero;
}
if (cmpres > 0 && mpz_cmp_ui(&a->mpz, (unsigned long int)1) == 0) {
INCREF(b);
return (object *)b;
}
if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long_int)0)) == 0) {
INCREF(mpz_value_zero);
return (object *)mpz_value_zero;
}
if (cmpres > 0 && mpz_cmp_ui(&b->mpz, (unsigned long int)1) == 0) {
INCREF(a);
return (object *)a;
}
#endif /* MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_mul( &z->mpz, &a->mpz, &b->mpz );
return (object *)z;
} /* mpz_multiply() */
static object *
mpz_divide(a, b)
mpzobject *a;
mpzobject *b;
{
#ifdef MPZ_SPARE_MALLOC
int cmpres;
#endif /* def MPZ_SPARE_MALLOC */
mpzobject *z;
if ((
#ifdef MPZ_SPARE_MALLOC
cmpres =
#endif /* def MPZ_SPARE_MALLOC */
mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) {
err_setstr(ZeroDivisionError, "mpz./ by zero");
return NULL;
}
#ifdef MPZ_SPARE_MALLOC
if (cmpres > 0 && mpz_cmp_ui(&b->mpz(unsigned long int)1) == 0) {
INCREF(a);
return (object *)a;
}
#endif /* def MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
#ifdef MPZ_TEST_DIV
fputs("mpz_divide: div result", stderr);
mpz_div(&z->mpz, &a->mpz, &b->mpz);
mpz_out_str(stderr, 10, &z->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
#ifdef MPZ_MDIV_BUG
if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0)
!= (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0)) {
/*
** numerator has other sign than denominator: we have
** to look at the remainder for a correction, since mpz_mdiv
** also calls mpz_divmod, I can as well do it myself
*/
MP_INT tmpmpz;
mpz_init(&tmpmpz);
mpz_divmod(&z->mpz, &tmpmpz, &a->mpz, &b->mpz);
if (mpz_cmp_ui(&tmpmpz, (unsigned long int)0) != 0)
mpz_sub_ui(&z->mpz, &z->mpz, (unsigned long int)1);
mpz_clear(&tmpmpz);
}
else
mpz_div(&z->mpz, &a->mpz, &b->mpz);
/* the ``naive'' implementation does it right for operands
having the same sign */
#else /* def MPZ_MDIV_BUG */
mpz_mdiv(&z->mpz, &a->mpz, &b->mpz);
#endif /* def MPZ_MDIV_BUG else */
#ifdef MPZ_TEST_DIV
fputs("mpz_divide: mdiv result", stderr);
mpz_out_str(stderr, 10, &z->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
return (object *)z;
} /* mpz_divide() */
static object *
mpz_remainder(a, b)
mpzobject *a;
mpzobject *b;
{
#ifdef MPZ_SPARE_MALLOC
int cmpres;
#endif /* def MPZ_SPARE_MALLOC */
mpzobject *z;
if ((
#ifdef MPZ_SPARE_MALLOC
cmpres =
#endif /* def MPZ_SPARE_MALLOC */
mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) {
err_setstr(ZeroDivisionError, "mpz.% by zero");
return NULL;
}
#ifdef MPZ_SPARE_MALLOC
if (cmpres > 0) {
if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)2)) == 0) {
INCREF(mpz_value_one);
return (object *)mpz_value_one;
}
if (cmpres < 0) {
/* b must be 1 now */
INCREF(mpz_value_zero);
return (object *)mpz_value_zero;
}
}
#endif /* def MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
#ifdef MPZ_TEST_DIV
fputs("mpz_remain: mod result", stderr);
mpz_mod(&z->mpz, &a->mpz, &b->mpz);
mpz_out_str(stderr, 10, &z->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
#ifdef MPZ_MDIV_BUG
/* the ``naive'' implementation does it right for operands
having the same sign */
mpz_mod(&z->mpz, &a->mpz, &b->mpz);
/* assumption: z, a and b all point to different locations */
if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0)
!= (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0)
&& mpz_cmp_ui(&z->mpz, (unsigned long int)0) != 0)
mpz_add(&z->mpz, &z->mpz, &b->mpz);
/*
** numerator has other sign than denominator: we have
** to look at the remainder for a correction, since mpz_mdiv
** also calls mpz_divmod, I can as well do it myself
*/
#else /* def MPZ_MDIV_BUG */
mpz_mmod(&z->mpz, &a->mpz, &b->mpz);
#endif /* def MPZ_MDIV_BUG else */
#ifdef MPZ_TEST_DIV
fputs("mpz_remain: mmod result", stderr);
mpz_out_str(stderr, 10, &z->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
return (object *)z;
} /* mpz_remainder() */
static object *
mpz_div_and_mod(a, b)
mpzobject *a;
mpzobject *b;
{
object *z = NULL;
mpzobject *x = NULL, *y = NULL;
if (mpz_cmp_ui(&b->mpz, (unsigned long int)0) == 0) {
err_setstr(ZeroDivisionError, "mpz.divmod by zero");
return NULL;
}
if ((z = newtupleobject(2)) == NULL
|| (x = newmpzobject()) == NULL
|| (y = newmpzobject()) == NULL) {
XDECREF(z);
XDECREF(x);
XDECREF(y);
return NULL;
}
#ifdef MPZ_TEST_DIV
fputs("mpz_divmod: dm result", stderr);
mpz_divmod(&x->mpz, &y->mpz, &a->mpz, &b->mpz);
mpz_out_str(stderr, 10, &x->mpz);
putc('\n', stderr);
mpz_out_str(stderr, 10, &y->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
#ifdef MPZ_MDIV_BUG
mpz_divmod(&x->mpz, &y->mpz, &a->mpz, &b->mpz);
if ((mpz_cmp_ui(&a->mpz, (unsigned long int)0) < 0)
!= (mpz_cmp_ui(&b->mpz, (unsigned long int)0) < 0)
&& mpz_cmp_ui(&y->mpz, (unsigned long int)0) != 0) {
/*
** numerator has other sign than denominator: we have
** to look at the remainder for a correction.
*/
mpz_add(&y->mpz, &y->mpz, &b->mpz);
mpz_sub_ui(&x->mpz, &x->mpz, (unsigned long int)1);
}
#else /* def MPZ_MDIV_BUG */
mpz_mdivmod( &x->mpz, &y->mpz, &a->mpz, &b->mpz );
#endif /* def MPZ_MDIV_BUG else */
#ifdef MPZ_TEST_DIV
fputs("mpz_divmod: mdm result", stderr);
mpz_out_str(stderr, 10, &x->mpz);
putc('\n', stderr);
mpz_out_str(stderr, 10, &y->mpz);
putc('\n', stderr);
#endif /* def MPZ_TEST_DIV */
(void)settupleitem(z, 0, (object *)x);
(void)settupleitem(z, 1, (object *)y);
return z;
} /* mpz_div_and_mod() */
static object *
mpz_power(a, b, m)
mpzobject *a;
mpzobject *b;
mpzobject *m;
{
mpzobject *z;
int cmpres;
long int longtmp1, longtmp2;
if ((object *)m!=Py_None)
{
mpzobject *z2;
INCREF(Py_None);
z=(mpzobject *)mpz_power(a, b, (mpzobject *)Py_None);
DECREF(Py_None);
if (z==NULL) return((object *)z);
z2=(mpzobject *)mpz_remainder(z, m);
DECREF(z);
return((object *)z2);
}
if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) {
/* the gnu-mp lib sets pow(0,0) to 0, we to 1 */
INCREF(mpz_value_one);
return (object *)mpz_value_one;
}
if (cmpres < 0) {
err_setstr(ValueError, "mpz.pow to negative exponent");
return NULL;
}
if ((cmpres = mpz_cmp_ui(&a->mpz, (unsigned long int)0)) == 0) {
/* the base is 0 */
INCREF(mpz_value_zero);
return (object *)mpz_value_zero;
}
else if (cmpres > 0
&& mpz_cmp_ui(&a->mpz, (unsigned long int)1) == 0) {
/* the base is 1 */
INCREF(mpz_value_one);
return (object *)mpz_value_one;
}
else if (cmpres < 0
&& mpz_cmp_si(&a->mpz, (long int)-1) == 0) {
MP_INT tmpmpz;
/* the base is -1: pow(-1, any) == 1,-1 for even,uneven b */
/* XXX this code needs to be optimized: what's better?
mpz_mmod_ui or mpz_mod_2exp, I choose for the latter
for *un*obvious reasons */
/* is the exponent even? */
mpz_init(&tmpmpz);
/* look to the remainder after a division by (1 << 1) */
mpz_mod_2exp(&tmpmpz, &b->mpz, (unsigned long int)1);
if (mpz_cmp_ui(&tmpmpz, (unsigned int)0) == 0) {
mpz_clear(&tmpmpz);
INCREF(mpz_value_one);
return (object *)mpz_value_one;
}
mpz_clear(&tmpmpz);
INCREF(mpz_value_mone);
return (object *)mpz_value_mone;
}
#ifdef MPZ_LIB_DOES_CHECKING
/* check if it's doable: sizeof(exp) > sizeof(long) &&
abs(base) > 1 ?? --> No Way */
if (mpz_size(&b->mpz) > 1)
return (object *)err_nomem();
#else /* def MPZ_LIB_DOES_CHECKING */
/* wet finger method */
if (mpz_cmp_ui(&b->mpz, (unsigned long int)0x10000) >= 0) {
err_setstr(ValueError, "mpz.pow outrageous exponent");
return NULL;
}
#endif /* def MPZ_LIB_DOES_CHECKING else */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_pow_ui(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz));
return (object *)z;
} /* mpz_power() */
static object *
mpz_negative(v)
mpzobject *v;
{
mpzobject *z;
#ifdef MPZ_SPARE_MALLOC
if (mpz_cmp_ui(&v->mpz, (unsigned long int)0) == 0) {
/* -0 == 0 */
INCREF(v);
return (object *)v;
}
#endif /* def MPZ_SPARE_MALLOC */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_neg(&z->mpz, &v->mpz);
return (object *)z;
} /* mpz_negative() */
static object *
mpz_positive(v)
mpzobject *v;
{
INCREF(v);
return (object *)v;
} /* mpz_positive() */
static object *
mpz_absolute(v)
mpzobject *v;
{
mpzobject *z;
if (mpz_cmp_ui(&v->mpz, (unsigned long int)0) >= 0) {
INCREF(v);
return (object *)v;
}
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_neg(&z->mpz, &v->mpz);
return (object *)z;
} /* mpz_absolute() */
static int
mpz_nonzero(v)
mpzobject *v;
{
return mpz_cmp_ui(&v->mpz, (unsigned long int)0) != 0;
} /* mpz_nonzero() */
static object *
mpz_invert(v)
mpzobject *v;
{
mpzobject *z;
/* I think mpz_com does exactly what needed */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_com(&z->mpz, &v->mpz);
return (object *)z;
} /* mpz_invert() */
static object *
mpz_lshift(a, b)
mpzobject *a;
mpzobject *b;
{
int cmpres;
mpzobject *z;
if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) {
/* a << 0 == a */
INCREF(a);
return (object *)a;
}
if (cmpres < 0) {
err_setstr(ValueError, "mpz.<< negative shift count");
return NULL;
}
#ifdef MPZ_LIB_DOES_CHECKING
if (mpz_size(&b->mpz) > 1)
return (object *)err_nomem();
#else /* def MPZ_LIB_DOES_CHECKING */
/* wet finger method */
if (mpz_cmp_ui(&b->mpz, (unsigned long int)0x10000) >= 0) {
err_setstr(ValueError, "mpz.<< outrageous shift count");
return NULL;
}
#endif /* def MPZ_LIB_DOES_CHECKING else */
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_mul_2exp(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz));
return (object *)z;
} /* mpz_lshift() */
static object *
mpz_rshift(a, b)
mpzobject *a;
mpzobject *b;
{
int cmpres;
mpzobject *z;
if ((cmpres = mpz_cmp_ui(&b->mpz, (unsigned long int)0)) == 0) {
/* a >> 0 == a */
INCREF(a);
return (object *)a;
}
if (cmpres < 0) {
err_setstr(ValueError, "mpz.>> negative shift count");
return NULL;
}
if (mpz_size(&b->mpz) > 1)
return (object *)err_nomem();
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_div_2exp(&z->mpz, &a->mpz, mpz_get_ui(&b->mpz));
return (object *)z;
} /* mpz_rshift() */
static object *
mpz_andfunc(a, b)
mpzobject *a;
mpzobject *b;
{
mpzobject *z;
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_and(&z->mpz, &a->mpz, &b->mpz);
return (object *)z;
} /* mpz_andfunc() */
/* hack Hack HAck HACk HACK, XXX this code is dead slow */
void
mpz_xor(res, op1, op2)
MP_INT *res;
const MP_INT *op1;
const MP_INT *op2;
{
MP_INT tmpmpz;
mpz_init(&tmpmpz);
mpz_and(res, op1, op2);
mpz_com(&tmpmpz, res);
mpz_ior(res, op1, op2);
mpz_and(res, res, &tmpmpz);
mpz_clear(&tmpmpz);
} /* mpz_xor() HACK */
static object *
mpz_xorfunc(a, b)
mpzobject *a;
mpzobject *b;
{
mpzobject *z;
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_xor(&z->mpz, &a->mpz, &b->mpz);
return (object *)z;
} /* mpz_xorfunc() */
static object *
mpz_orfunc(a, b)
mpzobject *a;
mpzobject *b;
{
mpzobject *z;
if ((z = newmpzobject()) == NULL)
return NULL;
mpz_ior(&z->mpz, &a->mpz, &b->mpz);
return (object *)z;
} /* mpz_orfunc() */
/* MPZ initialisation */
#include "longintrepr.h"
static object *
MPZ_mpz(self, args)
object *self;
object *args;
{
mpzobject *mpzp;
object *objp;
#ifdef MPZ_DEBUG
fputs("MPZ_mpz() called...\n", stderr);
#endif /* def MPZ_DEBUG */
if (!getargs(args, "O", &objp))
return NULL;
/* at least we know it's some object */
/* note DON't DECREF args NEITHER objp */
if (is_intobject(objp)) {
long lval;
if (!getargs(objp, "l", &lval))
return NULL;
if (lval == (long)0) {
INCREF(mpz_value_zero);
mpzp = mpz_value_zero;
}
else if (lval == (long)1) {
INCREF(mpz_value_one);
mpzp = mpz_value_one;
}
else if ((mpzp = newmpzobject()) == NULL)
return NULL;
else mpz_set_si(&mpzp->mpz, lval);
}
else if (is_longobject(objp)) {
MP_INT mplongdigit;
int i;
unsigned char isnegative;
if ((mpzp = newmpzobject()) == NULL)
return NULL;
mpz_set_si(&mpzp->mpz, 0L);
mpz_init(&mplongdigit);
/* how we're gonna handle this? */
if (isnegative = ((i = ((longobject *)objp)->ob_size) < 0) )
i = -i;
while (i--) {
mpz_set_ui(&mplongdigit,
(unsigned long)
((longobject *)objp)->ob_digit[i]);
mpz_mul_2exp(&mplongdigit,&mplongdigit,
(unsigned long int)i * SHIFT);
mpz_ior(&mpzp->mpz, &mpzp->mpz, &mplongdigit);
}
if (isnegative)
mpz_neg(&mpzp->mpz, &mpzp->mpz);
/* get rid of allocation for tmp variable */
mpz_clear(&mplongdigit);
}
else if (is_stringobject(objp)) {
char *cp;
int len;
MP_INT mplongdigit;
if (!getargs(objp, "s#", &cp, &len))
return NULL;
if ((mpzp = newmpzobject()) == NULL)
return NULL;
mpz_set_si(&mpzp->mpz, 0L);
mpz_init(&mplongdigit);
/* let's do it the same way as with the long conversion:
without thinking how it can be faster (-: :-) */
cp += len;
while (len--) {
mpz_set_ui(&mplongdigit, (unsigned long)*--cp );
mpz_mul_2exp(&mplongdigit,&mplongdigit,
(unsigned long int)len * 8);
mpz_ior(&mpzp->mpz, &mpzp->mpz, &mplongdigit);
}
/* get rid of allocation for tmp variable */
mpz_clear(&mplongdigit);
}
else if (is_mpzobject(objp)) {
INCREF(objp);
mpzp = (mpzobject *)objp;
}
else {
err_setstr(TypeError,
"mpz.mpz() expects integer, long, string or mpz object argument");
return NULL;
}
#ifdef MPZ_DEBUG
fputs("MPZ_mpz: created mpz=", stderr);
mpz_out_str(stderr, 10, &mpzp->mpz);
putc('\n', stderr);
#endif /* def MPZ_DEBUG */
return (object *)mpzp;
} /* MPZ_mpz() */
static mpzobject *
mpz_mpzcoerce(z)
object *z;
{
/* shortcut: 9 out of 10 times the type is already ok */
if (is_mpzobject(z)) {
INCREF(z);
return (mpzobject *)z; /* coercion succeeded */
}
/* what types do we accept?: intobjects and longobjects */
if (is_intobject(z) || is_longobject(z))
return (mpzobject *)MPZ_mpz((object *)NULL, z);
err_setstr(TypeError, "number coercion (to mpzobject) failed");
return NULL;
} /* mpz_mpzcoerce() */
/* Forward */
static void mpz_divm PROTO((MP_INT *res, const MP_INT *num,
const MP_INT *den, const MP_INT *mod));
static object *
MPZ_powm(self, args)
object *self;
object *args;
{
object *base, *exp, *mod;
mpzobject *mpzbase = NULL, *mpzexp = NULL, *mpzmod = NULL;
mpzobject *z;
int tstres;
if (!getargs(args, "(OOO)", &base, &exp, &mod))
return NULL;
if ((mpzbase = mpz_mpzcoerce(base)) == NULL
|| (mpzexp = mpz_mpzcoerce(exp)) == NULL
|| (mpzmod = mpz_mpzcoerce(mod)) == NULL
|| (z = newmpzobject()) == NULL) {
XDECREF(mpzbase);
XDECREF(mpzexp);
XDECREF(mpzmod);
return NULL;
}
if ((tstres=mpz_cmp_ui(&mpzexp->mpz, (unsigned long int)0)) == 0) {
INCREF(mpz_value_one);
return (object *)mpz_value_one;
}
if (tstres < 0) {
MP_INT absexp;
/* negative exp */
mpz_init_set(&absexp, &mpzexp->mpz);
mpz_abs(&absexp, &absexp);
mpz_powm(&z->mpz, &mpzbase->mpz, &absexp, &mpzmod->mpz);
mpz_divm(&z->mpz, &mpz_value_one->mpz, &z->mpz, &mpzmod->mpz);
mpz_clear(&absexp);
}
else {
mpz_powm(&z->mpz, &mpzbase->mpz, &mpzexp->mpz, &mpzmod->mpz);
}
DECREF(mpzbase);
DECREF(mpzexp);
DECREF(mpzmod);
return (object *)z;
} /* MPZ_powm() */
static object *
MPZ_gcd(self, args)
object *self;
object *args;
{
object *op1, *op2;
mpzobject *mpzop1 = NULL, *mpzop2 = NULL;
mpzobject *z;
if (!getargs(args, "(OO)", &op1, &op2))
return NULL;
if ((mpzop1 = mpz_mpzcoerce(op1)) == NULL
|| (mpzop2 = mpz_mpzcoerce(op2)) == NULL
|| (z = newmpzobject()) == NULL) {
XDECREF(mpzop1);
XDECREF(mpzop2);
return NULL;
}
/* ok, we have three mpzobjects, and an initialised result holder */
mpz_gcd(&z->mpz, &mpzop1->mpz, &mpzop2->mpz);
DECREF(mpzop1);
DECREF(mpzop2);
return (object *)z;
} /* MPZ_gcd() */
static object *
MPZ_gcdext(self, args)
object *self;
object *args;
{
object *op1, *op2, *z = NULL;
mpzobject *mpzop1 = NULL, *mpzop2 = NULL;
mpzobject *g = NULL, *s = NULL, *t = NULL;
if (!getargs(args, "(OO)", &op1, &op2))
return NULL;
if ((mpzop1 = mpz_mpzcoerce(op1)) == NULL
|| (mpzop2 = mpz_mpzcoerce(op2)) == NULL
|| (z = newtupleobject(3)) == NULL
|| (g = newmpzobject()) == NULL
|| (s = newmpzobject()) == NULL
|| (t = newmpzobject()) == NULL) {
XDECREF(mpzop1);
XDECREF(mpzop2);
XDECREF(z);
XDECREF(g);
XDECREF(s);
/*XDECREF(t);*/
return NULL;
}
mpz_gcdext(&g->mpz, &s->mpz, &t->mpz, &mpzop1->mpz, &mpzop2->mpz);
DECREF(mpzop1);
DECREF(mpzop2);
(void)settupleitem(z, 0, (object *)g);
(void)settupleitem(z, 1, (object *)s);
(void)settupleitem(z, 2, (object *)t);
return (object *)z;
} /* MPZ_gcdext() */
static object *
MPZ_sqrt(self, args)
object *self;
object *args;
{
object *op;
mpzobject *mpzop = NULL;
mpzobject *z;
if (!getargs(args, "O", &op))
return NULL;
if ((mpzop = mpz_mpzcoerce(op)) == NULL
|| (z = newmpzobject()) == NULL) {
XDECREF(mpzop);
return NULL;
}
mpz_sqrt(&z->mpz, &mpzop->mpz);
DECREF(mpzop);
return (object *)z;
} /* MPZ_sqrt() */
static object *
MPZ_sqrtrem(self, args)
object *self;
object *args;
{
object *op, *z = NULL;
mpzobject *mpzop = NULL;
mpzobject *root = NULL, *rem = NULL;
if (!getargs(args, "O", &op))
return NULL;
if ((mpzop = mpz_mpzcoerce(op)) == NULL
|| (z = newtupleobject(2)) == NULL
|| (root = newmpzobject()) == NULL
|| (rem = newmpzobject()) == NULL) {
XDECREF(mpzop);
XDECREF(z);
XDECREF(root);
/*XDECREF(rem);*/
return NULL;
}
mpz_sqrtrem(&root->mpz, &rem->mpz, &mpzop->mpz);
DECREF(mpzop);
(void)settupleitem(z, 0, (object *)root);
(void)settupleitem(z, 1, (object *)rem);
return (object *)z;
} /* MPZ_sqrtrem() */
static void
#if __STDC__
mpz_divm(MP_INT *res, const MP_INT *num, const MP_INT *den, const MP_INT *mod)
#else
mpz_divm(res, num, den, mod)
MP_INT *res;
const MP_INT *num;
const MP_INT *den;
const MP_INT *mod;
#endif
{
MP_INT s0, s1, q, r, x, d0, d1;
mpz_init_set(&s0, num);
mpz_init_set_ui(&s1, 0);
mpz_init(&q);
mpz_init(&r);
mpz_init(&x);
mpz_init_set(&d0, den);
mpz_init_set(&d1, mod);
while (d1.size != 0) {
mpz_divmod(&q, &r, &d0, &d1);
mpz_set(&d0, &d1);
mpz_set(&d1, &r);
mpz_mul(&x, &s1, &q);
mpz_sub(&x, &s0, &x);
mpz_set(&s0, &s1);
mpz_set(&s1, &x);
}
if (d0.size != 1 || d0.d[0] != 1)
res->size = 0; /* trouble: the gcd != 1; set s to zero */
else {
#ifdef MPZ_MDIV_BUG
/* watch out here! first check the signs, and then perform
the mpz_mod() since mod could point to res */
if ((s0.size < 0) != (mod->size < 0)) {
mpz_mod(res, &s0, mod);
if (res->size)
mpz_add(res, res, mod);
}
else
mpz_mod(res, &s0, mod);
#else /* def MPZ_MDIV_BUG */
mpz_mmod(res, &s0, mod);
#endif /* def MPZ_MDIV_BUG else */
}
mpz_clear(&s0);
mpz_clear(&s1);
mpz_clear(&q);
mpz_clear(&r);
mpz_clear(&x);
mpz_clear(&d0);
mpz_clear(&d1);
} /* mpz_divm() */
static object *
MPZ_divm(self, args)
object *self;
object *args;
{
object *num, *den, *mod;
mpzobject *mpznum, *mpzden, *mpzmod = NULL;
mpzobject *z = NULL;
if (!getargs(args, "(OOO)", &num, &den, &mod))
return NULL;
if ((mpznum = mpz_mpzcoerce(num)) == NULL
|| (mpzden = mpz_mpzcoerce(den)) == NULL
|| (mpzmod = mpz_mpzcoerce(mod)) == NULL
|| (z = newmpzobject()) == NULL ) {
XDECREF(mpznum);
XDECREF(mpzden);
XDECREF(mpzmod);
return NULL;
}
mpz_divm(&z->mpz, &mpznum->mpz, &mpzden->mpz, &mpzmod->mpz);
DECREF(mpznum);
DECREF(mpzden);
DECREF(mpzmod);
if (mpz_cmp_ui(&z->mpz, (unsigned long int)0) == 0) {
DECREF(z);
err_setstr(ValueError, "gcd(den, mod) != 1 or num == 0");
return NULL;
}
return (object *)z;
} /* MPZ_divm() */
/* MPZ methods-as-attributes */
#ifdef MPZ_CONVERSIONS_AS_METHODS
static object *
mpz_int(self, args)
mpzobject *self;
object *args;
#else /* def MPZ_CONVERSIONS_AS_METHODS */
static object *
mpz_int(self)
mpzobject *self;
#endif /* def MPZ_CONVERSIONS_AS_METHODS else */
{
long sli;
#ifdef MPZ_CONVERSIONS_AS_METHODS
if (!getnoarg(args))
return NULL;
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
if (mpz_size(&self->mpz) > 1
|| (sli = (long)mpz_get_ui(&self->mpz)) < (long)0 ) {
err_setstr(ValueError, "mpz.int() arg too long to convert");
return NULL;
}
if (mpz_cmp_ui(&self->mpz, (unsigned long)0) < 0)
sli = -sli;
return newintobject(sli);
} /* mpz_int() */
static object *
#ifdef MPZ_CONVERSIONS_AS_METHODS
mpz_long(self, args)
mpzobject *self;
object *args;
#else /* def MPZ_CONVERSIONS_AS_METHODS */
mpz_long(self)
mpzobject *self;
#endif /* def MPZ_CONVERSIONS_AS_METHODS else */
{
int i, isnegative;
unsigned long int uli;
longobject *longobjp;
int ldcount;
int bitpointer, newbitpointer;
MP_INT mpzscratch;
#ifdef MPZ_CONVERSIONS_AS_METHODS
if (!getnoarg(args))
return NULL;
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
/* determine length of python-long to be allocated */
if ((longobjp = alloclongobject(i = (int)
((mpz_size(&self->mpz) * BITS_PER_MP_LIMB
+ SHIFT - 1) /
SHIFT))) == NULL)
return NULL;
/* determine sign, and copy self to scratch var */
mpz_init_set(&mpzscratch, &self->mpz);
if (isnegative = (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0))
mpz_neg(&mpzscratch, &mpzscratch);
/* let those bits come, let those bits go,
e.g. dismantle mpzscratch, build longobject */
bitpointer = 0; /* the number of valid bits in stock */
newbitpointer = 0;
ldcount = 0; /* the python-long limb counter */
uli = (unsigned long int)0;
while (i--) {
longobjp->ob_digit[ldcount] = uli & MASK;
/* check if we've had enough bits for this digit */
if (bitpointer < SHIFT) {
uli = mpz_get_ui(&mpzscratch);
longobjp->ob_digit[ldcount] |=
(uli << bitpointer) & MASK;
uli >>= SHIFT-bitpointer;
bitpointer += BITS_PER_MP_LIMB;
mpz_div_2exp(&mpzscratch, &mpzscratch,
BITS_PER_MP_LIMB);
}
else
uli >>= SHIFT;
bitpointer -= SHIFT;
ldcount++;
}
assert(mpz_cmp_ui(&mpzscratch, (unsigned long int)0) == 0);
mpz_clear(&mpzscratch);
assert(ldcount <= longobjp->ob_size);
/* long_normalize() is file-static */
/* longobjp = long_normalize(longobjp); */
while (ldcount > 0 && longobjp->ob_digit[ldcount-1] == 0)
ldcount--;
longobjp->ob_size = ldcount;
if (isnegative)
longobjp->ob_size = -longobjp->ob_size;
return (object *)longobjp;
} /* mpz_long() */
/* I would have avoided pow() anyways, so ... */
static const double multiplier = 256.0 * 256.0 * 256.0 * 256.0;
#ifdef MPZ_CONVERSIONS_AS_METHODS
static object *
mpz_float(self, args)
mpzobject *self;
object *args;
#else /* def MPZ_CONVERSIONS_AS_METHODS */
static object *
mpz_float(self)
mpzobject *self;
#endif /* def MPZ_CONVERSIONS_AS_METHODS else */
{
int i, isnegative;
double x;
double mulstate;
MP_INT mpzscratch;
#ifdef MPZ_CONVERSIONS_AS_METHODS
if (!getnoarg(args))
return NULL;
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
i = (int)mpz_size(&self->mpz);
/* determine sign, and copy abs(self) to scratch var */
if (isnegative = (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0)) {
mpz_init(&mpzscratch);
mpz_neg(&mpzscratch, &self->mpz);
}
else
mpz_init_set(&mpzscratch, &self->mpz);
/* let those bits come, let those bits go,
e.g. dismantle mpzscratch, build floatobject */
x = 0.0;
mulstate = 1.0;
while (i--) {
x += mulstate * mpz_get_ui(&mpzscratch);
mulstate *= multiplier;
mpz_div_2exp(&mpzscratch, &mpzscratch, BITS_PER_MP_LIMB);
}
assert(mpz_cmp_ui(&mpzscratch, (unsigned long int)0) == 0);
mpz_clear(&mpzscratch);
if (isnegative)
x = -x;
return newfloatobject(x);
} /* mpz_float() */
#ifdef MPZ_CONVERSIONS_AS_METHODS
static object *
mpz_hex(self, args)
mpzobject *self;
object *args;
#else /* def MPZ_CONVERSIONS_AS_METHODS */
static object *
mpz_hex(self)
mpzobject *self;
#endif /* def MPZ_CONVERSIONS_AS_METHODS else */
{
#ifdef MPZ_CONVERSIONS_AS_METHODS
if (!getnoarg(args))
return NULL;
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
return mpz_format(self, 16, (unsigned char)1);
} /* mpz_hex() */
#ifdef MPZ_CONVERSIONS_AS_METHODS
static object *
mpz_oct(self, args)
mpzobject *self;
object *args;
#else /* def MPZ_CONVERSIONS_AS_METHODS */
static object *
mpz_oct(self)
mpzobject *self;
#endif /* def MPZ_CONVERSIONS_AS_METHODS else */
{
#ifdef MPZ_CONVERSIONS_AS_METHODS
if (!getnoarg(args))
return NULL;
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
return mpz_format(self, 8, (unsigned char)1);
} /* mpz_oct() */
static object *
mpz_binary(self, args)
mpzobject *self;
object *args;
{
int size;
stringobject *strobjp;
char *cp;
MP_INT mp;
unsigned long ldigit;
if (!getnoarg(args))
return NULL;
if (mpz_cmp_ui(&self->mpz, (unsigned long int)0) < 0) {
err_setstr(ValueError, "mpz.binary() arg must be >= 0");
return NULL;
}
mpz_init_set(&mp, &self->mpz);
size = (int)mpz_size(&mp);
if ((strobjp = (stringobject *)
newsizedstringobject((char *)0,
size * sizeof (unsigned long int))) == NULL)
return NULL;
/* get the beginning of the string memory and start copying things */
cp = GETSTRINGVALUE(strobjp);
/* this has been programmed using a (fairly) decent lib-i/f it could
be must faster if we looked into the GMP lib */
while (size--) {
ldigit = mpz_get_ui(&mp);
mpz_div_2exp(&mp, &mp, BITS_PER_MP_LIMB);
*cp++ = (unsigned char)(ldigit & 0xFF);
*cp++ = (unsigned char)((ldigit >>= 8) & 0xFF);
*cp++ = (unsigned char)((ldigit >>= 8) & 0xFF);
*cp++ = (unsigned char)((ldigit >>= 8) & 0xFF);
}
while (strobjp->ob_size && !*--cp)
strobjp->ob_size--;
return (object *)strobjp;
} /* mpz_binary() */
static struct methodlist mpz_methods[] = {
#ifdef MPZ_CONVERSIONS_AS_METHODS
{"int", mpz_int},
{"long", mpz_long},
{"float", mpz_float},
{"hex", mpz_hex},
{"oct", mpz_oct},
#endif /* def MPZ_CONVERSIONS_AS_METHODS */
{"binary", (object *(*)(object *, object *))mpz_binary},
{NULL, NULL} /* sentinel */
};
static object *
mpz_getattr(self, name)
mpzobject *self;
char *name;
{
return findmethod(mpz_methods, (object *)self, name);
} /* mpz_getattr() */
static int
mpz_coerce(pv, pw)
object **pv;
object **pw;
{
object *z;
#ifdef MPZ_DEBUG
fputs("mpz_coerce() called...\n", stderr);
#endif /* def MPZ_DEBUG */
assert(is_mpzobject(*pv));
/* always convert other arg to mpz value, except for floats */
if (!is_floatobject(*pw)) {
if ((z = (object *)mpz_mpzcoerce(*pw)) == NULL)
return -1; /* -1: an error always has been set */
INCREF(*pv);
*pw = z;
}
else {
if ((z = mpz_float(*pv, NULL)) == NULL)
return -1;
INCREF(*pw);
*pv = z;
}
return 0; /* coercion succeeded */
} /* mpz_coerce() */
static object *
mpz_repr(v)
object *v;
{
return mpz_format(v, 10, (unsigned char)1);
} /* mpz_repr() */
#define UF (unaryfunc)
#define BF (binaryfunc)
#define TF (ternaryfunc)
#define IF (inquiry)
#define CF (coercion)
static number_methods mpz_as_number = {
BF mpz_addition, /*nb_add*/
BF mpz_substract, /*nb_subtract*/
BF mpz_multiply, /*nb_multiply*/
BF mpz_divide, /*nb_divide*/
BF mpz_remainder, /*nb_remainder*/
BF mpz_div_and_mod, /*nb_divmod*/
TF mpz_power, /*nb_power*/
UF mpz_negative, /*nb_negative*/
UF mpz_positive, /*tp_positive*/
UF mpz_absolute, /*tp_absolute*/
IF mpz_nonzero, /*tp_nonzero*/
UF mpz_invert, /*nb_invert*/
BF mpz_lshift, /*nb_lshift*/
BF mpz_rshift, /*nb_rshift*/
BF mpz_andfunc, /*nb_and*/
BF mpz_xorfunc, /*nb_xor*/
BF mpz_orfunc, /*nb_or*/
CF mpz_coerce, /*nb_coerce*/
#ifndef MPZ_CONVERSIONS_AS_METHODS
UF mpz_int, /*nb_int*/
UF mpz_long, /*nb_long*/
UF mpz_float, /*nb_float*/
UF mpz_oct, /*nb_oct*/
UF mpz_hex, /*nb_hex*/
#endif /* ndef MPZ_CONVERSIONS_AS_METHODS */
};
static typeobject MPZtype = {
OB_HEAD_INIT(&Typetype)
0, /*ob_size*/
"mpz", /*tp_name*/
sizeof(mpzobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor)mpz_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)mpz_getattr, /*tp_getattr*/
0, /*tp_setattr*/
(cmpfunc)mpz_compare, /*tp_compare*/
(reprfunc)mpz_repr, /*tp_repr*/
&mpz_as_number, /*tp_as_number*/
};
/* List of functions exported by this module */
static struct methodlist mpz_functions[] = {
#if 0
{initialiser_name, MPZ_mpz},
#else /* 0 */
/* until guido ``fixes'' struct methodlist */
{(char *)initialiser_name, MPZ_mpz},
#endif /* 0 else */
{"powm", MPZ_powm},
{"gcd", MPZ_gcd},
{"gcdext", MPZ_gcdext},
{"sqrt", MPZ_sqrt},
{"sqrtrem", MPZ_sqrtrem},
{"divm", MPZ_divm},
{NULL, NULL} /* Sentinel */
};
/* #define MP_TEST_ALLOC */
#ifdef MP_TEST_ALLOC
#define MP_TEST_SIZE 4
static const char mp_test_magic[MP_TEST_SIZE] = {'\xAA','\xAA','\xAA','\xAA'};
static mp_test_error( location )
int *location;
{
/* assumptions: *alloc returns address dividable by 4,
mpz_* routines allocate in chunks dividable by four */
fprintf(stderr, "MP_TEST_ERROR: location holds 0x%08d\n", *location );
fatal("MP_TEST_ERROR");
} /* static mp_test_error() */
#define MP_EXTRA_ALLOC(size) ((size) + MP_TEST_SIZE)
#define MP_SET_TEST(basep,size) (void)memcpy( ((char *)(basep))+(size), mp_test_magic, MP_TEST_SIZE)
#define MP_DO_TEST(basep,size) if ( !memcmp( ((char *)(basep))+(size), mp_test_magic, MP_TEST_SIZE ) ) \
; \
else \
mp_test_error((int *)((char *)(basep) + size))
#else /* def MP_TEST_ALLOC */
#define MP_EXTRA_ALLOC(size) (size)
#define MP_SET_TEST(basep,size)
#define MP_DO_TEST(basep,size)
#endif /* def MP_TEST_ALLOC else */
void *mp_allocate( alloc_size )
size_t alloc_size;
{
void *res;
#ifdef MPZ_DEBUG
fprintf(stderr, "mp_allocate : size %ld\n",
alloc_size);
#endif /* def MPZ_DEBUG */
if ( (res = malloc(MP_EXTRA_ALLOC(alloc_size))) == NULL )
fatal("mp_allocate failure");
#ifdef MPZ_DEBUG
fprintf(stderr, "mp_allocate : address 0x%08x\n", res);
#endif /* def MPZ_DEBUG */
MP_SET_TEST(res,alloc_size);
return res;
} /* mp_allocate() */
void *mp_reallocate( ptr, old_size, new_size )
void *ptr;
size_t old_size;
size_t new_size;
{
void *res;
#ifdef MPZ_DEBUG
fprintf(stderr, "mp_reallocate: old address 0x%08x, old size %ld\n",
ptr, old_size);
#endif /* def MPZ_DEBUG */
MP_DO_TEST(ptr, old_size);
if ( (res = realloc(ptr, MP_EXTRA_ALLOC(new_size))) == NULL )
fatal("mp_reallocate failure");
#ifdef MPZ_DEBUG
fprintf(stderr, "mp_reallocate: new address 0x%08x, new size %ld\n",
res, new_size);
#endif /* def MPZ_DEBUG */
MP_SET_TEST(res, new_size);
return res;
} /* mp_reallocate() */
void mp_free( ptr, size )
void *ptr;
size_t size;
{
#ifdef MPZ_DEBUG
fprintf(stderr, "mp_free : old address 0x%08x, old size %ld\n",
ptr, size);
#endif /* def MPZ_DEBUG */
MP_DO_TEST(ptr, size);
free(ptr);
} /* mp_free() */
/* Initialize this module. */
void
initmpz()
{
#ifdef MPZ_DEBUG
fputs( "initmpz() called...\n", stderr );
#endif /* def MPZ_DEBUG */
mp_set_memory_functions( mp_allocate, mp_reallocate, mp_free );
(void)initmodule("mpz", mpz_functions);
/* create some frequently used constants */
if ((mpz_value_zero = newmpzobject()) == NULL)
fatal("initmpz: can't initialize mpz constants");
mpz_set_ui(&mpz_value_zero->mpz, (unsigned long int)0);
if ((mpz_value_one = newmpzobject()) == NULL)
fatal("initmpz: can't initialize mpz constants");
mpz_set_ui(&mpz_value_one->mpz, (unsigned long int)1);
if ((mpz_value_mone = newmpzobject()) == NULL)
fatal("initmpz: can't initialize mpz constants");
mpz_set_si(&mpz_value_mone->mpz, (long)-1);
} /* initmpz() */
#ifdef MAKEDUMMYINT
int _mpz_dummy_int; /* XXX otherwise, we're .bss-less (DYNLOAD->Jack?) */
#endif /* def MAKEDUMMYINT */
|