-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDecInt.py
2284 lines (1946 loc) · 70.7 KB
/
DecInt.py
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
'''Implement decimal arithmetic on very large integers.
Example
=============================================================================
>>> import DecInt
>>> bigprime = DecInt.DecInt(2) ** 74207281 -1
>>> len(str(bigprime))
22338618
>>>
History
=============================================================================
DecInt was inspired by a Tim Peters posting on comp.lang.python of a minimal
BigDec class that was used to find the decimal representation of Mersenne
primes.
Performance
=============================================================================
Conversion to/from a decimal string in O(n) instead of O(n^2). This was the
primary motivation for developing DecInt.
For small- to medium-sized numbers, multiplication (kmult) uses a combination
of 2x2 (aka Karatsuba), 3x3, and 4x4 Toom-Cook multiplication algorithms.
The resulting algorithm is O(n^~1.4) compared to O(n^~1.585) for the
built-in multiplication. The kmult function is measurably faster than the
native Python multiplication when working with integers of approximately
200,000 digits.
For large numbers, Nussbaumer convolution (nussmult) is used for multiplica-
tion. The running time for Nussbaumer convolution is O(n ln(n)). The cross-
over point between Toom-Cook and Nussbaumer multiplication is approximately
300,000 digits.
Division uses two different algorithms. For a (relatively) small divisor,
David M. Smith's O(n^2) algorithm (smithdiv) is used. It quite efficient
since it doesn't require propagation of carries during intermediate steps.
For larger divisors, division uses a new algorithm (kdiv) that modifies David
M. Smith's O(n^2) algorithm with very fast intermediate steps. The running
time of this algorithm is O(n ln(n)^2).
For improved performance, GMPY2 is used when it is available.
References
=============================================================================
1) Crandall, R. E. "Topics in Advanced Scientific Computation", Springer-
Verlag
2) Hollerback, U. "Fast Multiplication & Division of Very Large Numbers."
sci.math.research posting, Jan. 23, 1996.
3) Knuth, D. E. "The Art of Computer Programming, Vol. 2: Seminumerical
Algorithms, 3rd ed.", Addison-Wesley
4) Smith, D. M. "A Multiple-Precision Division Algorithm", Mathematics of
Computation (1996)
Release History
=============================================================================
Version 0.1
-----------
This was the first release.
Version 0.2
-----------
A bug fix release.
Version 0.3
-----------
Renamed to DecInt from BigDecimal to avoid confusion with the decimal module
included with Python.
Multiplication of very large numbers now uses Nussbaumer convolution.
Various performance tweaks.
Version 0.4
-----------
Converted to a single file.
Bug fixes.
Added examples: pell()
Version 0.5
-----------
Support Python 2.7 and Python 3.x.
Do not attempt to use psyco.
Requirements
=============================================================================
Python 2.7 or later
gmpy and psyco are used if present. gmpy 1.01 is required.
Todo
=============================================================================
1) More examples.
2) Faster gcd() and related functions.
3) Allow use of an arbitrary radix. The underlying code in mpops.py
should work with an arbitrary radix. I'm not sure of a reasonable
format to use for the __str__ representation for an arbitrary radix.
License
=============================================================================
Copyright (c) 2004-2005, 2016 Case Van Horsen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================
The Nussbaumer convolution code is based on software released under the
following license:
Copyright (c) 2005 Perfectly Scientific, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Contact
=============================================================================
casevh@gmail.com
'''
from __future__ import print_function
# Import random so we can create large integers with random digits.
import random
_rr = random.Random(42)
import operator
import math
# Try to use the gmpy2 module to get faster operations.
try:
import gmpy2
mp = gmpy2.mpz
GMPY_Loaded = True
try:
int_types = (int, long, type(mp(1)))
except NameError:
int_types = (int, type(mp(1)))
except ImportError:
try:
mp = long
except NameError:
mp = int
GMPY_Loaded = False
try:
int_types = (int, long)
except NameError:
int_types = (int)
# Initialize some commonly used values.
ZERO = mp(0)
ONE = mp(1)
TWO = mp(2)
THREE = mp(3)
FOUR = mp(4)
FIVE = mp(5)
SIX = mp(6)
EIGHT = mp(8)
NINE = mp(9)
TWO7 = mp(27)
TWO4 = mp(24)
ONE20 = mp(120)
EIGHT1 = mp(81)
SEVEN29 = mp(729)
ONE6 = mp(16)
SIX4 = mp(64)
M_ONE = mp(-1)
M_TWO = mp(-2)
M_THREE = mp(-3)
M_FOUR = mp(-4)
M_EIGHT = mp(-8)
M_NINE = mp(-9)
M_ONE6 = mp(-16)
M_TWO7 = mp(-27)
M_EIGHT1 = mp(-81)
# Division is noticably faster when the length of quotient consists of a
# small number of large and small powers of 2. DIVFAST controls whether or
# not the number of digits per term is adjusted to make the length of the
# quotient optimal.
#
# DIV_CUTOFF defines the threshold above which optimization occurs. The
# value is the product of the number of terms in the divisor and quotient.
DIVFAST = True
DIV_CUTOFF = 1000 * 100
# Define constants for the Nussbaumer convolution algorithm.
CYC_CUTOFF = 8
NEG_CUTOFF = 8
# Define some helper functions that do element-wise operations on lists.
# The lengths of the two lists are assumed to be equal. The map() command
# is the fastest way to add or subtract two lists if you are NOT using psyco.
# If psyco is available, a plain old loop is fastest.
def add(x, y):
'''Return elementwise sum of two lists.'''
return [ a+b for a,b in zip(x,y) ]
def sub(x, y):
'''Return elementwise difference of two lists.'''
return [ a-b for a,b in zip(x,y) ]
def minus(x):
'''Return list with all elements negated.'''
return [ -a for a in x ]
def mul(n, xlst):
'''Return elementwise multiplication of a list and a number.'''
return [ n * i for i in xlst ]
def shiftright(n, xlst):
'''Return list with all elements shifted right n bits.'''
return [i >> n for i in xlst]
def shiftleft(n, xlst):
'''Return list with all elements shifted left n bits.'''
return [i << n for i in xlst]
# Optimize some frequent combinations.
def lcomb2(a, x, b, y):
'''Return the linear combination ax + by.'''
return [ a*xx + b*yy for xx,yy in zip(x,y) ]
def lcomb2a(x, b, y):
'''Return the linear combination x + by.'''
return [ xx + b*yy for xx,yy in zip(x,y) ]
def lcomb3(a, x, b, y, c, z):
'''Return the linear combination ax + by + cz.'''
return [ a**xx + b*yy +c*zz for xx,yy,zz in zip(x,y,z) ]
def lcomb3a(x, b, y, c, z):
'''Return the linear combination x + by + cz.'''
return [ xx + b*yy + c*zz for xx,yy,zz in zip(x,y,z) ]
def lcomb4a(x, b, y, c, z, d, t):
'''Return the linear combination x + by + cz + dt.'''
return [ xx + b*yy + c*zz +d*tt for xx,yy,zz,tt in zip(x,y,z,t) ]
# Define functions used to convert to/from a single number.
# To improve the speed of "tolong2" which repeatedly squares the radix
# value, we keep a cache of radix values and we only pass the base and power
# around.
# radix is a tuple that defines the radix used. The tuple contains base and
# power of the radix. For example, to work with groups of one hundred
# base-10 digits, use (100,10).
RadixCache = {}
def Radix2Value(radix):
'''Return radix[1] ** radix[0], caching values for reuse.'''
return RadixCache.setdefault(radix, mp(radix[1]) ** radix[0])
def tolong(x, radix):
'''Converts an MP integer into a single number.
You should really use tolong2, it is much faster.'''
RADIX = Radix2Value(radix)
res = ZERO
for term in reversed(x):
res = (res * RADIX) + term
return res
def tolong2(x, radix):
'''Fast conversion of MP integer into a single number.'''
power, base = radix
while len(x) > 1:
temp = []
for i in range(0, len(x), 2):
temp.append(tolong(x[i:i+2], (power, base)))
x = temp
power *= 2
return x[0]
def fromlong(x, radix):
'''Converts a long into an MP integer.'''
RADIX = Radix2Value(radix)
if x == 0:
return [ZERO]
else:
res = []
while x:
x, temp = divmod(x, RADIX)
res.append(temp)
return res
def fromlong2(x, radix):
'''Fast conversion of a long into an MP integer.'''
# First estimate how many decimal digits there will be.
try:
# This works for gmpy.mpz, long, and ints.
hexrep = hex(x)
hexlen = len(hexrep)
if hexrep.endswith('L'):
hexlen -= 1
except TypeError:
raise TypeError('Error is conversion to hex().')
declen = int(math.ceil(hexlen * math.log(16) / math.log(10)))
# We will recursively divide x into approximately equal sized portions
# until we get down to the length of an individual term.
power, base = radix
divlen = power
powerlist = [(divlen, base)]
while divlen < declen:
divlen *= 2
powerlist.append((divlen, base))
temp = [x]
for divval in reversed(powerlist):
temp1 = []
for bv in temp:
temp1.extend(divmod(bv, Radix2Value(divval)))
if temp1[0] == 0:
temp = temp1[1:]
else:
temp = temp1
temp.reverse()
return temp
def smalldiv(lst, n, radix):
'''Divide the elements of a list by a small number.
Since all the uses require that the final remainder is zero, there is
an assert test to verify that.
Note: does not remove leading zeros from the result because kmult
assumes the lengths of the list do not change.'''
RADIX = Radix2Value(radix)
res = [ZERO] * len(lst)
rem = ZERO
for indx in reversed(range(len(lst))):
res[indx], rem = divmod(lst[indx] + rem * RADIX, n)
assert rem == ZERO
return res
def subsmalldiv(lsta, lstb, n, radix):
'''Return (lsta - lstb) div n.
Same as smalldiv(sub(lsta, lstb), n, radix).'''
RADIX = Radix2Value(radix)
res = [ZERO] * len(lsta)
rem = ZERO
for indx in reversed(range(len(lsta))):
res[indx], rem = divmod(lsta[indx] - lstb[indx] + rem * RADIX, n)
assert rem == ZERO
return res
def addsmalldiv(lsta, lstb, n, radix):
'''Return (lsta + lstb) div n.
Same as smalldiv(add(lsta, lstb), n, radix).'''
RADIX = Radix2Value(radix)
res = [ZERO] * len(lsta)
rem = ZERO
for indx in reversed(range(len(lsta))):
res[indx], rem = divmod(lsta[indx] + lstb[indx] + rem * RADIX, n)
assert rem == ZERO
return res
def smalldivmod(lst, n , radix):
'''Divide elements of a list by a small number and return remainder.
Just like smalldiv about except that it does remove leading zeros and
it also returns the remainder.
'''
RADIX = Radix2Value(radix)
res = [ZERO] * len(lst)
rem = ZERO
for indx in reversed(range(len(lst))):
res[indx], rem = divmod(lst[indx] + rem * RADIX, n)
while len(res) > 1 and res[-1] == ZERO:
res.pop()
return (res, rem)
# Begin Karatsuba and Toom-Cook multiplication here!!!
def kmul2x2s(x, y):
'''Perform a 2x2 Toom-Cook (aka Karatsuba) multiplication.
Multiply two 2-element lists using three multiplications and
four additions.
'''
z = [ZERO] * 3
x0, x1 = x
y0, y1 = y
z[0] = x0 * y0
z[2] = x1 * y1
z[1] = (x0 + x1) * (y0 + y1) - z[0] - z[2]
return z
def kmul3x3s(x, y):
'''Perform a 3x3 Toom-Cook multiplication of two 3-element lists.
Multiply two 3-element lists using five multiplications, some
additions and some divisions by a small value.
'''
z = [ZERO] * 5
x0, x1, x2 = x
y0 ,y1, y2 = y
z[0] = x0 * y0
z[4] = x2 * y2
t1 = (x0 + x1 + x2) * (y0 + y1 + y2)
t2 = (x0 - x1 + x2) * (y0 - y1 + y2)
t3 = (x0 + (x1 << ONE) + (x2 << TWO)) * (y0 + (y1 << ONE) + (y2 << TWO))
z[2] = ((t1 + t2) >> ONE) - z[0] - z[4]
t4 = t3 - z[0] - (z[2] << TWO) - (z[4] << FOUR)
z[3] = (t4 - t1 + t2) // SIX
z[1] = ((t1 - t2) >> ONE) - z[3]
return z
def kmul4x4s(x, y):
'''Perform a 4x4 Toom-Cook multiplication of two 4-element lists.
Multiply two 4-element lists using seven multiplications, some
additions and some divisions by a small value.
The code looks ugly, but it is just solving five equations with five
unknowns.
'''
z = [ZERO] * 7
x0, x1, x2, x3 = x
y0, y1, y2, y3 = y
z[0] = x0 * y0
z[6] = x3 * y3
t0 = z[0] + z[6]
xeven = x0 + x2
xodd = x1 + x3
yeven = y0 + y2
yodd = y1 + y3
t1 = ((xeven + xodd) * (yeven + yodd)) - t0
t2 = ((xeven - xodd) * (yeven - yodd)) - t0
xeven = x0 + (x2 << TWO)
xodd = (x1 << ONE) + (x3 << THREE)
yeven = y0 + (y2 << TWO)
yodd = (y1 << ONE) + (y3 << THREE)
t0 = z[0] + (z[6] << SIX)
t3 = (xeven + xodd) * (yeven + yodd) - t0
t4 = (xeven - xodd) * (yeven - yodd) - t0
t5 = ((x0 + THREE * x1 + NINE * x2 + TWO7 * x3) *
(y0 + THREE * y1 + NINE * y2 + TWO7 * y3)) -\
(z[0] + SEVEN29 * z[6])
t6 = t1 + t2
t7 = t3 + t4
z[4] = (t7 - (t6 << TWO)) // TWO4
z[2] = (t6 >> ONE) - z[4]
t8 = t1 - z[2] - z[4]
t9 = t3 - (z[2] << TWO) - (z[4] << FOUR)
t10 = t5 - NINE * z[2] - EIGHT1 * z[4]
t11 = t10 - THREE * t8
t12 = t9 - (t8 << ONE)
z[5] = (t11 - (t12 << TWO)) // ONE20
z[3] = ((t12 << THREE) - t11) // TWO4
z[1] = t8 - z[3] - z[5]
return z
def kmul2x2l(x, y, radix):
'''Do the recursion for the 2Nx2N Karatsuba multiply.
'''
ysplit = (len(y) + 1) // 2
z = [ZERO] * (len(x) + len(y) - 1)
x0 = x[: ysplit]
x1 = x[ysplit :]
y0 = y[: ysplit]
y1 = y[ysplit :]
z0 = kmult(x0, y0, radix)
z2 = kmult(x1, y1, radix)
z[2 * ysplit :] = z2
x1.extend([ZERO] * (ysplit - len(x1)))
y1.extend([ZERO] * (ysplit - len(y1)))
z2.extend([ZERO] * (2*ysplit - 1 - len(z2)))
t1 = kmult(add(x0, x1), add(y0, y1), radix)
z1 = sub(sub(t1, z0), z2)
z[: len(z0)] = z0
while len(z1) > 1 and z1[-1] == ZERO:
z1.pop()
z[ysplit : ysplit + len(z1)] = add(z1, z[ysplit : ysplit + len(z1)])
return z
def kmul8x8l(x, y, radix):
'''Special case multiplication for 8x8 lists.'''
z = [ZERO] * (15)
x0, x1 = x[:4], x[4:]
y0, y1 = y[:4], y[4:]
z0 = kmul4x4s(x0, y0)
z2 = kmul4x4s(x1, y1)
z1 = kmul4x4s(add(x0, x1), add(y0, y1))
z[8:] = z2
z[:7] = z0
for i, term in enumerate(z1):
z[4 + i] += term - z0[i] - z2[i]
return z
def kmul3x3l(x, y, radix):
'''Do the recursion for the 3Nx3N Toom-Cook multiply.
'''
ysplit = (len(y) + 2) // 3
y0 = y[: ysplit]
y1 = y[ysplit : 2*ysplit]
y2 = y[2*ysplit :]
z = [ZERO] * (len(x) + len(y) - 1)
x0 = x[: ysplit]
x1 = x[ysplit : 2*ysplit]
x2 = x[2*ysplit :]
z0 = kmult(x0, y0, radix)
z4 = kmult(x2, y2, radix)
z[4*ysplit :] = z4
x2.extend([ZERO] * (ysplit - len(x2)))
y2.extend([ZERO] * (ysplit - len(y2)))
z4.extend([ZERO] * (2*ysplit - len(z4) - 1))
xeven = add(x0, x2)
yeven = add(y0, y2)
t1 = kmult(add(xeven, x1), add(yeven, y1), radix)
t2 = kmult(sub(xeven, x1), sub(yeven, y1), radix)
t3 = kmult(add(x0, add(add(x1, x1), mul(FOUR, x2))),
add(y0, add(add(y1, y1), mul(FOUR, y2))), radix)
z2 = sub(addsmalldiv(t1, t2, TWO, radix), add(z0, z4))
t5 = sub(sub(t3, z0), add(mul(FOUR, z2), mul(ONE6, z4)))
t6 = sub(t1, t2)
z3 = subsmalldiv(t5, t6, SIX, radix)
z1 = sub(smalldiv(t6, TWO, radix), z3)
z[: len(z0)] = z0
z[2 * ysplit : 4*ysplit - 1] = z2
z[ysplit : 3*ysplit - 1] = add(z1, z[ysplit : 3*ysplit - 1])
while len(z3) > 1 and z3[-1] == ZERO:
z3.pop()
z[3*ysplit : 3*ysplit + len(z3)] = add(z3, z[3*ysplit : 3*ysplit + len(z3)])
return z
def kmul4x4l(x, y, radix):
'''Do the recursion for the 4Nx4N Toom-Cook multiply.
'''
z = [ZERO] * (len(x) + len(y) - 1)
ysplit = (len(y) + 3) // 4
# Consider x and y as polynomials:
# x(t) = x0 + x1*t + x2*t^2 + x3*t^3
# y(t) = y0 + y1*t + y2*t^2 + y3*t^3
y0 = y[:ysplit]
y1 = y[ysplit:2*ysplit]
y2 = y[2*ysplit:3*ysplit]
y3 = y[3*ysplit:]
x0 = x[:ysplit]
x1 = x[ysplit:2*ysplit]
x2 = x[2*ysplit:3*ysplit]
x3 = x[3*ysplit:]
# Compute z(t) = x(t) * y(t) at several values of t, then solve for the
# coefficients of z(t). There are 7 unknowns, but two (z0 and z6) are
# trivial to solve. This means we need to solve 5 equations with 5
# unknowns.
z0 = kmult(x0, y0, radix)
z6 = kmult(x3, y3, radix)
z[6*ysplit :] = z6
# Need to fix the situation when the length of x and y is not exactly
# divisible by 4. The algorithm would be a cleaner if the lengths were
# ZERO-padded first, but this is a little faster.
x3.extend([ZERO] * (ysplit - len(x3)))
y3.extend([ZERO] * (ysplit - len(y3)))
z6.extend([ZERO] * (2 * ysplit - 1 - len(z6)))
# Compute z(1) & z(-1).
xeven = add(x0, x2)
xodd = add(x1, x3)
yeven = add(y0, y2)
yodd = add(y1, y3)
tmp = add(z0, z6)
t1 = sub(kmult(add(xeven, xodd), add(yeven, yodd), radix), tmp)
t2 = sub(kmult(sub(xeven, xodd), sub(yeven, yodd), radix), tmp)
# Compute z(2) & z(-2).
xeven = lcomb2a(x0, FOUR, x2)
xodd = lcomb2(TWO, x1, EIGHT, x3)
yeven = lcomb2a(y0, FOUR, y2)
yodd = lcomb2(TWO, y1, EIGHT, y3)
t0 = lcomb2a(z0, SIX4, z6)
t3 = subsmalldiv(kmult(add(xeven, xodd),
add(yeven, yodd), radix),
t0, TWO, radix)
t4 = subsmalldiv(kmult(sub(xeven, xodd),
sub(yeven, yodd), radix),
t0, TWO, radix)
# Compute z(-3).
t5 = subsmalldiv(kmult(lcomb4a(x0, THREE, x1, NINE, x2, TWO7, x3),
lcomb4a(y0, THREE, y1, NINE, y2, TWO7, y3), radix),
lcomb2a(z0, SEVEN29, z6), THREE, radix)
# Brute force solving for 5 unknowns from 5 equations.
t6 = addsmalldiv(t1, t2, TWO, radix)
t7 = addsmalldiv(t3, t4, FOUR, radix)
z4 = subsmalldiv(t7, t6, THREE, radix)
z2 = sub(t6, z4)
t8 = lcomb3a(t1, M_ONE, z2, M_ONE, z4)
t9 = lcomb3a(t3, M_TWO, z2, M_EIGHT, z4)
t10 = lcomb3a(t5, M_THREE, z2, M_TWO7, z4)
t11 = subsmalldiv(t10, t8, EIGHT, radix)
t12 = subsmalldiv(t9, t8, THREE, radix)
z5 = subsmalldiv(t11, t12, FIVE, radix)
z3 = sub(add(t12, t12), t11)
z1 = sub(t8, add(z3, z5))
z[:len(z0)] = z0
z[2*ysplit : 4*ysplit - 1] = z2
z[4*ysplit : 6*ysplit - 1] = z4
z[ysplit : 3*ysplit - 1] = add(z1, z[ysplit : 3*ysplit - 1])
z[3*ysplit : 5*ysplit - 1] = add(z3, z[3*ysplit : 5*ysplit - 1])
while len(z5) > 1 and z5[-1] == ZERO:
z5.pop()
z[5*ysplit : 5*ysplit + len(z5)] = add(z5, z[5*ysplit : 5*ysplit + len(z5)])
return z
def kmult(x, y, radix):
'''Perform recursive Toom-Cook multiplication on two lists of longs.
kmult uses a combination of 2x2 (Karatsuba), 3x3, and 4x4 Toom-Cook
multiplication algorithms.
'''
# Let x be the longest number.
if len(x) < len(y):
x, y = y, x
xlen = len(x)
ylen = len(y)
# Begin by handling some of the simple special cases.
if ylen == 1:
return mul(y[0], x)
if ylen == 2:
if xlen == 2:
return kmul2x2s(x, y)
else:
# Do 2xN multiplication.
z = [ZERO]
for ptr in range(0, xlen, 2):
temp = kmult(x[ptr : ptr + 2], y, radix)
z[-1] += temp[0]
z.extend(temp[1:])
return z
if ylen == 3:
if xlen == 3:
return kmul3x3s(x, y)
else:
# Do 3xN multiplication.
z = [ZERO] * 2
for ptr in range(0, xlen, 3):
temp = kmult(x[ptr : ptr + 3], y, radix)
z[-2] += temp[0]
z[-1] += temp[1]
z.extend(temp[2:])
return z
if ylen == 4:
if xlen == 4:
return kmul4x4s(x, y)
else:
# Do 4xN multiplication.
z = [ZERO] * 3
for ptr in range(0, xlen, 4):
temp = kmult(x[ptr : ptr + 4], y, radix)
z[-3] += temp[0]
z[-2] += temp[1]
z[-1] += temp[2]
z.extend(temp[3:])
return z
# All the special cases have been done. Now for the real work.
if xlen == ylen:
if xlen < 8:
return kmul2x2l(x, y, radix)
elif xlen == 8:
return kmul8x8l(x, y, radix)
elif xlen <= 12:
return kmul3x3l(x, y, radix)
else:
return kmul4x4l(x, y, radix)
else:
z = []
for ptr in range(0, xlen, ylen):
temp = kmult(x[ptr : ptr + ylen], y, radix)
z[ptr:] = add(temp[:len(z) - ptr], z[ptr:])
z.extend(temp[len(z) - ptr:])
return z
# End of Karatsuba and Toom-Cook multiplication.
# Begin Nussbaumer convolution code here!!!
# References:
# 1) "The Art of Computer Programming, Volume 2: Seminumerical Algorithms",
# Donald Knuth, Section 4.6.4, Problem 59
# 2) "Topics in Advanced Scientific Computation", Richard E. Crandall
# 3) http://www.perfsci.com/freegoods.htm#fastalgorithms
def log2(n):
'''Return int(log-base-2(n))'''
res = -1
while n:
res += 1
n >>= 1
return res
def cyclit(x, y, radix):
'''Return cyclic convolution of lists x and y.
Uses Toom-Cook multiplication as defined above.'''
assert len(x) == len(y)
n = len(x)
if n == 8:
temp = kmul8x8l(x, y, radix)
elif n == 4:
temp = kmul4x4s(x, y)
else:
temp = kmult(x, y, radix)
res = temp[:n]
res[:n-1] = add(res[:n-1], temp[n:])
return res
def neglit(x, y, radix):
'''Return nega-cyclic convolution of lists x and y.
Uses Toom-Cook multiplication as defined above.'''
assert len(x) == len(y)
n = len(x)
if n == 8:
temp = kmul8x8l(x, y, radix)
elif n == 4:
temp = kmul4x4s(x, y)
else:
temp = kmult(x, y, radix)
res = temp[:n]
res[:n-1] = sub(res[:n-1], temp[n:])
return res
def makepoly(a, r, m):
# Create the zero extended polynomials for Nussbaumer convolution.
res = []
for i in range(m):
res.append(a[i::m])
res.extend([ [ZERO] * r for i in range(m) ])
return res
def unpoly(a, r, m):
# Inverse of makepoly.
res = []
for i in range(r):
for j in range(m):
res.append(a[j][i])
return res
def twist(aterm, r, q):
q %= 2*r
if q == 0:
return aterm
elif q < r:
v = r - q
return minus(aterm[v:]) + aterm[:v]
else:
q -= r
v = r - q
return aterm[v:] + minus(aterm[:v])
def neg(x, y, radix):
'''Recursive negacyclic convolution.'''
assert len(x) == len(y)
n = len(x)
if n <= NEG_CUTOFF:
return neglit(x, y, radix)
pow = log2(n)
assert 2 ** pow == n
m = 1 << (pow // 2)
r = n // m
w = r // m
a = makepoly(x, r, m)
b = makepoly(y, r, m)
k = m
# Do the forward FFT.
while k > 0:
v = w * m // k
u = 0
for j in range(k):
i = j
while i < 2 * m:
s = i
t = i + k
a_s = a[s]
at = a[t]
bs = b[s]
bt = b[t]
for g in range(r):
a_s[g], at[g] = a_s[g] + at[g], a_s[g] - at[g]
bs[g], bt[g] = bs[g] + bt[g], bs[g] - bt[g]
a[t] = twist(a[t], r, u)
b[t] = twist(b[t], r, u)
i += 2 * k
u += v
k //= 2
# Do the recursion!
c = [ neg(a[i], b[i], radix) for i in range(2*m) ]
# Do the DIT IFFT.
k = 1
while k < 2* m:
v = -w * m // k
u = 0
for j in range(k):
i = j
while i < 2*m:
s = i
t = i + k
c[t] = twist(c[t], r, u)
ct = c[t]
cs = c[s]
for g in range(r):
cs[g], ct[g] = cs[g] + ct[g], cs[g] - ct[g]
i += 2*k
u += v
k *= 2
for k in range(m-1):
s = k
t = k + m
c[t] = twist(c[t], r, 1)
ct = c[t]
cs = c[s]
for g in range(r):
cs[g] += ct[g]
d = unpoly(c, r, m)
return shiftright(mp(1 + pow // 2), d)
def neg_sqr(x, radix):
'''Recursive negacyclic convolution squaring.'''
n = len(x)
if n <= NEG_CUTOFF:
return neglit(x, x, radix)
pow = log2(n)
assert 2 ** pow == n
m = 1 << (pow // 2)
r = n // m
w = r // m
a = makepoly(x, r, m)
k = m
# Do the forward FFT.
while k > 0:
v = w * m // k
u = 0
for j in range(k):
i = j
while i < 2 * m:
s = i
t = i + k
a_s = a[s]
at = a[t]
for g in range(r):
a_s[g], at[g] = a_s[g] + at[g], a_s[g] - at[g]
a[t] = twist(a[t], r, u)
i += 2 * k
u += v
k //= 2
# Do the recursion!
c = [ neg_sqr(a[i], radix) for i in range(2*m) ]
# Do the DIT IFFT.
k = 1
while k < 2* m:
v = -w * m // k
u = 0
for j in range(k):
i = j
while i < 2*m:
s = i
t = i + k
c[t] = twist(c[t], r, u)
ct = c[t]
cs = c[s]
for g in range(r):
cs[g], ct[g] = cs[g] + ct[g], cs[g] - ct[g]
i += 2*k
u += v
k *= 2
for k in range(m-1):
s = k
t = k + m
c[t] = twist(c[t], r, 1)
ct = c[t]
cs = c[s]
for g in range(r):
cs[g] += ct[g]
d = unpoly(c, r, m)
return shiftright(mp(1 + pow // 2), d)
def cyc(x, y, radix):
'''Recursive cyclic convolution (Nussbaumer convolution).'''
assert len(x) == len(y)
n = len(x)
assert 2 ** log2(n) == n
nhalf = n >> 1
if n <= CYC_CUTOFF:
return cyclit(x, y, radix)
rcyc = cyc(add(x[:nhalf], x[nhalf:]), add(y[:nhalf], y[nhalf:]), radix)
rneg = neg(sub(x[:nhalf], x[nhalf:]), sub(y[:nhalf], y[nhalf:]), radix)
return shiftright(1, add(rcyc, rneg) + sub(rcyc, rneg))
def cyc_sqr(x, radix):
'''Recursive cyclic convolution squaring.'''
n = len(x)
assert 2 ** log2(n) == n
nhalf = n >> 1
if n <= CYC_CUTOFF:
return cyclit(x, x, radix)
xplus = add(x[:nhalf], x[nhalf:])
xminus = sub(x[:nhalf], x[nhalf:])
rcyc = cyc_sqr(xplus, radix)
rneg = neg_sqr(xminus, radix)
return shiftright(1, add(rcyc, rneg) + sub(rcyc, rneg))
def nussmult(x, y, radix):
'''Multiply two lists of longs using the Nussbaumer convolution algorithm.
Still need to add more intelligence about when to use kmult and how
to handle x and y with radically different lengths. Currently, the shorter
list is padded to the same length as the padded longer list.'''
n = max(len(x), len(y))
pow = log2(n)
if 2 ** pow < n:
pow += 1
newn = 2 ** (pow + 1)
z = cyc(x + ([ZERO] * (newn - len(x))),
y + ([ZERO] * (newn - len(y))), radix)
return z[:len(x) + len(y) - 1]
def nuss_square(x, radix):
'''Square a list of longs using the Nussbaumer convolution algorithm.