/
pyecm.py
executable file
·1483 lines (1191 loc) · 40.6 KB
/
pyecm.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
#!/usr/bin/python3
'''
You should install psyco and gmpy if you want maximal speed.
Filename: pyecm
Authors: Eric Larson <elarson3@uoregon.edu>, Martin Kelly <martin@martingkelly.com>, Matt Ford <zeotherm@gmail.com>
License: GNU GPL (see <http://www.gnu.org/licenses/gpl.html> for more information.
Description: Factors a number using the Elliptic Curve Method, a fast algorithm for numbers < 50 digits.
We are using curves in Suyama's parametrization, but points are in affine coordinates, and the curve is in Wierstrass form.
The idea is to do many curves in parallel to take advantage of batch inversion algorithms. This gives asymptotically 7 modular multiplications per bit.
WARNING: pyecm is NOT a general-purpose number theory or elliptic curve library. Many of the functions have confusing calling syntax, and some will rather unforgivingly crash or return bad output if the input is not formatted exactly correctly. That said, there are a couple of functions that you CAN safely import into another program. These are: factors, isprime. However, be sure to read the documentation for each function that you use.
'''
import math
import sys
import random
try:
import psyco
psyco.full()
PSYCO_EXISTS = True
except ImportError:
PSYCO_EXISTS = False
try: # Try to use gmpy
from gmpy2 import isqrt as sqrt
from gmpy2 import iroot as root
from gmpy2 import gcd, invert, mpz, next_prime
import gmpy2
GMPY_EXISTS = True
except ImportError:
try:
from gmpy import gcd, invert, mpz, next_prime, sqrt, root
GMPY_EXISTS = True
except ImportError:
GMPY_EXISTS = False
if not GMPY_EXISTS:
PRIMES = (5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 167)
GMPY_EXISTS = False
def gcd(a, b):
'''Computes the Greatest Common Divisor of a and b using the standard quadratic time improvement to the Euclidean Algorithm.
Returns the GCD of a and b.'''
if b == 0:
return a
elif a == 0:
return b
count = 0
if a < 0:
a = -a
if b < 0:
b = -b
while not ((a & 1) | (b & 1)):
count += 1
a >>= 1
b >>= 1
while not a & 1:
a >>= 1
while not b & 1:
b >>= 1
if b > a:
b,a = a,b
while b != 0 and a != b:
a -= b
while not (a & 1):
a >>= 1
if b > a:
b, a = a, b
return a << count
def invert(a, b):
'''Computes the inverse of a modulo b. b must be odd.
Returns the inverse of a (mod b).'''
if a == 0 or b == 0:
return 0
truth = False
if a < 0:
truth = True
a = -a
b_orig = b
alpha = 1
beta = 0
while not a & 1:
if alpha & 1:
alpha += b_orig
alpha >>= 1
a >>= 1
if b > a:
a, b = b, a
alpha, beta = beta, alpha
while b != 0 and a != b:
a -= b
alpha -= beta
while not a & 1:
if alpha & 1:
alpha += b_orig
alpha >>= 1
a >>= 1
if b > a:
a,b = b,a
alpha, beta = beta, alpha
if a == b:
a -= b
alpha -= beta
a, b = b, a
alpha, beta = beta, alpha
if a != 1:
return 0
if truth:
alpha = b_orig - alpha
return alpha
def next_prime(n):
'''Finds the next prime after n.
Returns the next prime after n.'''
n += 1
if n <= 167:
if n <= 23:
if n <= 3:
return 3 - (n <= 2)
n += (n & 1) ^ 1
return n + (((4 - (n % 3)) >> 1) & 2)
n += (n & 1) ^ 1
inc = n % 3
n += ((4 - inc) >> 1) & 2
inc = 6 - ((inc + ((2 - inc) & 2)) << 1)
while 0 in (n % 5, n % 7, n % 11):
n += inc
inc = 6 - inc
return n
n += (n & 1) ^ 1
inc = n % 3
n += ((4 - inc) >> 1) & 2
inc = 6 - ((inc + ((2 - inc) & 2)) << 1)
should_break = False
while 1:
for prime in PRIMES:
if not n % prime:
should_break = True
break
if should_break:
should_break = False
n += inc
inc = 6 - inc
continue
p = 1
for i in range(int(math.log(n) / LOG_2), 0, -1):
p <<= (n >> i) & 1
p = (p * p) % n
if p == 1:
return n
n += inc
inc = 6 - inc
def mpz(n):
'''A dummy function to ensure compatibility with those that do not have gmpy.
Returns n.'''
return n
def root(n, k):
'''Finds the floor of the kth root of n. This is a duplicate of gmpy's root function.
Returns a tuple. The first item is the floor of the kth root of n. The second is 1 if the root is exact (as in, sqrt(16)) and 0 if it is not.'''
low = 0
high = n + 1
while high > low + 1:
mid = (low + high) >> 1
mr = mid**k
if mr == n:
return (mid, 1)
if mr < n:
low = mid
if mr > n:
high = mid
return (low, 0)
def sqrt(n):
return root(n, 2)[0]
# We're done importing. Now for some constants.
if GMPY_EXISTS:
INV_C = 1.4
else:
if PSYCO_EXISTS:
INV_C = 7.3
else:
INV_C = 13.0
LOG_2 = math.log(2)
LOG_4 = math.log(4)
LOG_3_MINUS_LOG_LOG_2 = math.log(3) - math.log(LOG_2)
LOG_4_OVER_9 = LOG_4 / 9
_3_OVER_LOG_2 = 3 / LOG_2
_5_LOG_10 = 5 * math.log(10)
_7_OVER_LOG_2 = 7 / LOG_2
BIG = 2.0**512
BILLION = 10**9 # Something big that fits into an int.
MULT = math.log(3) / LOG_2
ONE = mpz(1)
SMALL = 2.0**(-30)
SMALLEST_COUNTEREXAMPLE_FASTPRIME = 2047
T = (type(mpz(1)), type(1), type(1))
DUMMY = 'dummy' # Dummy value throughout the program
VERSION = '2.0.5 (Python 3)'
_12_LOG_2_OVER_49 = 12 * math.log(2) / 49
RECORD = 1162795072109807846655696105569042240239
class ts:
'''Does basic manipulations with Taylor Series (centered at 0). An example call to ts:
a = ts(7, 23, [1<<23, 2<<23, 3<<23]) -- now, a represents 1 + 2x + 3x^2. Here, computations will be done to degree 7, with accuracy 2^(-23). Input coefficients must be integers.'''
def __init__(self, degree, acc, p):
self.acc = acc
self.coefficients = p[:degree + 1]
while len(self.coefficients) <= degree:
self.coefficients.append(0)
def add(self, a, b):
'''Adds a and b'''
b_ = b.coefficients[:]
a_ = a.coefficients[:]
self.coefficients = []
while len(b_) > len(a_):
a_.append(0)
while len(b_) < len(a_):
b_.append(0)
for i in range(len(a_)):
self.coefficients.append(a_[i] + b_[i])
self.acc = a.acc
def ev(self, x):
'''Returns a(x)'''
answer = 0
for i in range(len(self.coefficients) - 1, -1, -1):
answer *= x
answer += self.coefficients[i]
return answer
def evh(self):
'''Returns a(1/2)'''
answer = 0
for i in range(len(self.coefficients) - 1, -1, -1):
answer >>= 1
answer += self.coefficients[i]
return answer
def evmh(self):
'''Returns a(-1/2)'''
answer = 0
for i in range(len(self.coefficients) - 1, -1, -1):
answer = - answer >> 1
answer += self.coefficients[i]
return answer
def int(self):
'''Replaces a by an integral of a'''
self.coefficients = [0] + self.coefficients
for i in range(1, len(self.coefficients)):
self.coefficients[i] = self.coefficients[i] // i
def lindiv(self, a):
'''a.lindiv(k) -- sets a/(x-k/2) for integer k'''
for i in range(len(self.coefficients) - 1):
self.coefficients[i] <<= 1
self.coefficients[i] = self.coefficients[i] // a
self.coefficients[i + 1] -= self.coefficients[i]
self.coefficients[-1] <<= 1
self.coefficients[-1] = self.coefficients[-1] // a
def neg(self):
'''Sets a to -a'''
for i in range(len(self.coefficients)):
self.coefficients[i] = - self.coefficients[i]
def set(self, a):
'''a.set(b) sets a to b'''
self.coefficients = a.coefficients[:]
self.acc = a.acc
def simp(self):
'''Turns a into a type of Taylor series that can be fed into ev, but cannot be computed with further.'''
for i in range(len(self.coefficients)):
shift = max(0, int(math.log(abs(self.coefficients[i]) + 1) / LOG_2) - 1000)
self.coefficients[i] = float(self.coefficients[i] >> shift)
shift = self.acc - shift
for _ in range(shift >> 9):
self.coefficients[i] /= BIG
self.coefficients[i] /= 2.0**(shift & 511)
if (abs(self.coefficients[i] / self.coefficients[0]) <= SMALL):
self.coefficients = self.coefficients[:i]
break
# Functions are declared in alphabetical order except when dependencies force them to be at the end.
def add(p1, p2, n):
'''Adds first argument to second (second argument is not preserved). The arguments are points on an elliptic curve. The first argument may be a tuple instead of a list. The addition is thus done pointwise. This function has bizzare input/output because there are fast algorithms for inverting a bunch of numbers at once.
Returns a list of the addition results.'''
inv = list(range(len(p1)))
for i in range(len(p1)):
inv[i] = p1[i][0] - p2[i][0]
inv = parallel_invert(inv, n)
if not isinstance(inv, list):
return inv
for i in range(len(p1)):
m = ((p1[i][1] - p2[i][1]) * inv[i]) % n
p2[i][0] = (m * m - p1[i][0] - p2[i][0]) % n
p2[i][1] = (m * (p1[i][0] - p2[i][0]) - p1[i][1]) % n
return p2
def add_sub_x_only(p1, p2, n):
'''Given a pair of lists of points p1 and p2, computes the x-coordinates of
p1[i] + p2[i] and p1[i] - p2[i] for each i.
Returns two lists, the first being the sums and the second the differences.'''
sums = list(range(len(p1)))
difs = list(range(len(p1)))
for i in range(len(p1)):
sums[i] = p2[i][0] - p1[i][0]
sums = parallel_invert(sums, n)
if not isinstance(sums, list):
return (sums, None)
for i in range(len(p1)):
ms = ((p2[i][1] - p1[i][1]) * sums[i]) % n
md = ((p2[i][1] + p1[i][1]) * sums[i]) % n
sums[i] = (ms * ms - p1[i][0] - p2[i][0]) % n
difs[i] = (md * md - p1[i][0] - p2[i][0]) % n
sums = tuple(sums)
difs = tuple(difs)
return (sums, difs)
def atdn(a, d, n):
'''Calculates a to the dth power modulo n.
Returns the calculation's result.'''
x = 1
pos = int(math.log(d) / LOG_2)
while pos >= 0:
x = (x * x) % n
if (d >> pos) & 1:
x *= a
pos -= 1
return x % n
def copy(p):
'''Copies a list using only deep copies.
Returns a copy of p.'''
answer = []
for i in p:
answer.append(i[:])
return answer
def could_be_prime(n):
'''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits.
Returns whether it is possible for n to be prime (True or False).
'''
if n < 2:
return False
if n == 2:
return True
if not int(n) & 1:
return False
product = ONE
log_n = int(math.log(n)) + 1
bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1
if bound * log_n >= n:
bound = 1
log_n = int(sqrt(n))
prime_bound = 0
prime = 3
for _ in range(bound):
p = []
prime_bound += log_n
while prime <= prime_bound:
p.append(prime)
prime = next_prime(prime)
if p != []:
p = prod(p)
product = (product * p) % n
return gcd(n, product) == 1
def double(p, n):
'''Doubles each point in the input list. Much like the add function, we take advantage of fast inversion.
Returns the doubled list.'''
inv = list(range(len(p)))
for i in range(len(p)):
inv[i] = p[i][1] << 1
inv = parallel_invert(inv, n)
if not isinstance(inv, list):
return inv
for i in range(len(p)):
x = p[i][0]
m = (x * x) % n
m = ((m + m + m + p[i][2]) * inv[i]) % n
p[i][0] = (m * m - x - x) % n
p[i][1] = (m * (x - p[i][0]) - p[i][1]) % n
return p
def fastprime(n):
'''Tests for primality of n using an algorithm that is very fast, O(N**3 / log(N)) (assuming quadratic multiplication) where n has N digits, but ocasionally inaccurate for n >= 2047.
Returns the primality of n (True or False).'''
if not could_be_prime(n):
return False
if n == 2:
return True
j = 1
d = n >> 1
while not d & 1:
d >>= 1
j += 1
p = 1
pos = int(math.log(d) / LOG_2)
while pos >= 0:
p = (p * p) % n
p <<= (d >> pos) & 1
pos -= 1
if p in (n - 1, n + 1):
return True
for _ in range(j):
p = (p * p) % n
if p == 1:
return False
elif p == n - 1:
return True
return False
def greatest_n(phi_max):
'''Finds the greatest n such that phi(n) < phi_max.
Returns the greatest n such that phi(n) < phi_max.'''
phi_product = 1
product = 1
prime = 1
while phi_product <= phi_max:
prime = next_prime(prime)
phi_product *= prime - 1
product *= prime
n_max = (phi_max * product) // phi_product
phi_values = list(range(n_max))
prime = 2
while prime <= n_max:
for i in range(0, n_max, prime):
phi_values[i] -= phi_values[i] // prime
prime = next_prime(prime)
for i in range(n_max - 1, 0, -1):
if phi_values[i] <= phi_max:
return i
def inv_const(n):
'''Finds a constant relating the complexity of multiplication to that of modular inversion.
Returns the constant for a given n.'''
return int(INV_C * math.log(n)**0.42)
def naf(d):
'''Finds a number's non-adjacent form, reverses the bits, replaces the
-1's with 3's, and interprets the result base 4.
Returns the result interpreted as if in base 4.'''
g = 0
while d:
g <<= 2
g ^= ((d & 2) & (d << 1)) ^ (d & 1)
d += (d & 2) >> 1
d >>= 1
return g
def parallel_invert(l, n):
'''Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion.
Returns the list with all elements inverted modulo 3(n-1).'''
l_ = l[:]
for i in range(len(l)-1):
l[i+1] = (l[i] * l[i+1]) % n
try:
inv = invert(l[-1], n)
except ZeroDivisionError:
inv = 0
if inv == 0:
return gcd(l[-1], n)
for i in range(len(l)-1, 0, -1):
l[i] = (inv * l[i-1]) % n
inv = (inv * l_[i]) % n
l[0] = inv
return l
def prod(p):
'''Multiplies all elements of a list together. The order in which the
elements are multiplied is chosen to take advantage of Python's Karatsuba
Multiplication
Returns the product of everything in p.'''
jump = 1
while jump < len(p):
for i in range(0, len(p) - jump, jump << 1):
p[i] *= p[i + jump]
p[i + jump] = None
jump <<= 1
return p[0]
def rho_ev(x, ts):
'''Evaluates Dickman's rho function, which calculates the asymptotic
probability as N approaches infinity (for a given x) that all of N's factors
are bounded by N^(1/x).'''
return ts[int(x)].ev(x - int(x) - 0.5)
def rho_ts(n):
'''Makes a list of Taylor series for the rho function centered at 0.5, 1.5, 2.5 ... n + 0.5. The reason this is necessary is that the radius of convergence of rho is small, so we need lots of Taylor series centered at different places to correctly evaluate it.
Returns a list of Taylor series.'''
f = ts(10, 10, [])
answer = [ts(10, 10, [1])]
for _ in range(n):
answer.append(ts(10, 10, [1]))
deg = 5
acc = 50 + n * int(1 + math.log(1 + n) + math.log(math.log(3 + n)))
r = 1
rho_series = ts(1, 10, [0])
while r != rho_series.coefficients[0]:
deg = (deg + (deg << 2)) // 3
r = rho_series.coefficients[0]
rho_series = ts(deg, acc, [(1) << acc])
center = 0.5
for i in range(1, n+1):
f.set(rho_series)
center += 1
f.lindiv(int(2*center))
f.int()
f.neg()
d = ts(deg, acc, [rho_series.evh() - f.evmh()])
f.add(f, d)
rho_series.set(f)
f.simp()
answer[i].set(f)
rho_series.simp()
return answer
def sub_sub_sure_factors(f, u, curve_parameter):
'''Finds all factors that can be found using ECM with a smoothness bound of u and sigma and give curve parameters. If that fails, checks for being a prime power and does Fermat factoring as well.
Yields factors.'''
while not (f & 1):
yield 2
f >>= 1
while not (f % 3):
yield 3
f = f // 3
if isprime(f):
yield f
return
log_u = math.log(u)
u2 = int(_7_OVER_LOG_2 * u * log_u / math.log(log_u))
primes = []
still_a_chance = True
log_mo = math.log(f + 1 + sqrt(f << 2))
g = gcd(curve_parameter, f)
if g not in (1, f):
for factor in sub_sub_sure_factors(g, u, curve_parameter):
yield factor
for factor in sub_sub_sure_factors(f//g, u, curve_parameter):
yield factor
return
g2 = gcd(curve_parameter**2 - 5, f)
if g2 not in (1, f):
for factor in sub_sub_sure_factors(g2, u, curve_parameter):
yield factor
for factor in sub_sub_sure_factors(f // g2, u, curve_parameter):
yield factor
return
if f in (g, g2):
yield f
while still_a_chance:
p1 = get_points([curve_parameter], f)
for prime in primes:
p1 = multiply(p1, prime, f)
if not isinstance(p1, list):
if p1 != f:
for factor in sub_sub_sure_factors(p1, u, curve_parameter):
yield factor
for factor in sub_sub_sure_factors(f//p1, u, curve_parameter):
yield factor
return
else:
still_a_chance = False
break
if not still_a_chance:
break
prime = 1
still_a_chance = False
while prime < u2:
prime = next_prime(prime)
should_break = False
for _ in range(int(log_mo / math.log(prime))):
p1 = multiply(p1, prime, f)
if not isinstance(p1, list):
if p1 != f:
for factor in sub_sub_sure_factors(p1, u, curve_parameter):
yield factor
for factor in sub_sub_sure_factors(f//p1, u, curve_parameter):
yield factor
return
else:
still_a_chance = True
primes.append(prime)
should_break = True
break
if should_break:
break
for i in range(2, int(math.log(f) / LOG_2) + 2):
r = root(f, i)
if r[1]:
for factor in sub_sub_sure_factors(r[0], u, curve_parameter):
for _ in range(i):
yield factor
return
a = 1 + sqrt(f)
bsq = a * a - f
iter = 0
while bsq != sqrt(bsq)**2 and iter < 3:
a += 1
iter += 1
bsq += a + a - 1
if bsq == sqrt(bsq)**2:
b = sqrt(bsq)
for factor in sub_sub_sure_factors(a - b, u, curve_parameter):
yield factor
for factor in sub_sub_sure_factors(a + b, u, curve_parameter):
yield factor
return
yield f
return
def sub_sure_factors(f, u, curve_params):
'''Factors n as far as possible using the fact that f came from a mainloop call.
Yields factors of n.'''
if len(curve_params) == 1:
for factor in sub_sub_sure_factors(f, u, curve_params[0]):
yield factor
return
c1 = curve_params[:len(curve_params) >> 1]
c2 = curve_params[len(curve_params) >> 1:]
if mainloop(f, u, c1) == 1:
for factor in sub_sure_factors(f, u, c2):
yield factor
return
if mainloop(f, u, c2) == 1:
for factor in sub_sure_factors(f, u, c1):
yield factor
return
for factor in sub_sure_factors(f, u, c1):
if isprime(factor):
yield factor
else:
for factor_of_factor in sub_sure_factors(factor, u, c2):
yield factor_of_factor
return
def subtract(p1, p2, n):
'''Given two points on an elliptic curve, subtract them pointwise.
Returns the resulting point.'''
inv = list(range(len(p1)))
for i in range(len(p1)):
inv[i] = p2[i][0] - p1[i][0]
inv = parallel_invert(inv, n)
if not isinstance(inv, list):
return inv
for i in range(len(p1)):
m = ((p1[i][1] + p2[i][1]) * inv[i]) % n
p2[i][0] = (m * m - p1[i][0] - p2[i][0]) % n
p2[i][1] = (m * (p1[i][0] - p2[i][0]) + p1[i][1]) % n
return p2
def congrats(f, veb):
'''Prints a congratulations message when a record factor is found. This only happens if the second parameter (verbosity) is set to True.
Returns nothing.'''
if veb and f > RECORD:
print('Congratulations! You may have found a record factor via pyecm!')
print('Please email the Mainloop call to Eric Larson <elarson3@uoregon.edu>')
return
def sure_factors(n, u, curve_params, veb, ra, ov, tdb, pr):
'''Factor n as far as possible with given smoothness bound and curve parameters, including possibly (but very rarely) calling ecm again.
Yields factors of n.'''
f = mainloop(n, u, curve_params)
if f == 1:
return
if veb:
print('Found factor:', f)
print('Mainloop call was:', n, u, curve_params)
if isprime(f):
congrats(f, veb)
yield f
n = n//f
if isprime(n):
yield n
if veb:
print('(factor processed)')
return
for factor in sub_sure_factors(f, u, curve_params):
if isprime(factor):
congrats(f, veb)
yield factor
else:
if veb:
print('entering new ecm loop to deal with stubborn factor:', factor)
for factor_of_factor in ecm(factor, True, ov, veb, tdb, pr):
yield factor_of_factor
n = n//factor
if isprime(n):
yield n
if veb:
print('(factor processed)')
return
def to_tuple(p):
'''Converts a list of two-element lists into a list of two-element tuples.
Returns a list.'''
answer = []
for i in p:
answer.append((i[0], i[1]))
return tuple(answer)
def mainloop(n, u, p1):
''' Input: n -- an integer to (try) to factor.
u -- the phase 1 smoothness bound
p1 -- a list of sigma parameters to try
Output: A factor of n. (1 is returned on faliure).
Notes:
1. Other parameters, such as the phase 2 smoothness bound are selected by the mainloop function.
2. This function uses batch algorithms, so if p1 is not long enough, there will be a loss in efficiency.
3. Of course, if p1 is too long, then the mainloop will have to use more memory.
[The memory is polynomial in the length of p1, log u, and log n].'''
k = inv_const(n)
log_u = math.log(u)
log_log_u = math.log(log_u)
log_n = math.log(n)
u2 = int(_7_OVER_LOG_2 * u * log_u / log_log_u)
ncurves = len(p1)
w = int(math.sqrt(_3_OVER_LOG_2 * ncurves / k) - 0.5)
number_of_primes = int((ncurves << w) * math.sqrt(LOG_4_OVER_9 * log_n / k) / log_u) # Lagrange multipliers!
number_of_primes = min(number_of_primes, int((log_n / math.log(log_n))**2 * ncurves / log_u), int(u / log_u))
number_of_primes = max(number_of_primes, 1)
m = math.log(number_of_primes) + log_log_u
w = min(w, int((m - 2 * math.log(m) + LOG_3_MINUS_LOG_LOG_2) / LOG_2))
w = max(w, 1)
max_order = n + sqrt(n << 2) + 1 # By Hasse's theorem.
det_bound = ((1 << w) - 1 + ((w & 1) << 1)) // 3
log_mo = math.log(max_order)
p = list(range(number_of_primes))
prime = mpz(2)
p1 = get_points(p1, n)
if not isinstance(p1, list):
return p1
for _ in range(int(log_mo / LOG_2)):
p1 = double(p1, n)
if not isinstance(p1, list):
return p1
for i in range(1, det_bound):
prime = (i << 1) + 1
if isprime(prime):
for _ in range(int(log_mo / math.log(prime))):
p1 = multiply(p1, prime, n)
if not isinstance(p1, list):
return p1
while prime < sqrt(u) and isinstance(p1, list):
for i in range(number_of_primes):
prime = next_prime(prime)
p[i] = prime ** max(1, int(log_u / math.log(prime)))
p1 = fast_multiply(p1, prod(p), n, w)
if not isinstance(p1, list):
return p1
while prime < u and isinstance(p1, list):
for i in range(number_of_primes):
prime = next_prime(prime)
p[i] = prime
p1 = fast_multiply(p1, prod(p), n, w)
if not isinstance(p1, list):
return p1
del p
small_jump = int(greatest_n((1 << (w + 2)) // 3))
small_jump = max(120, small_jump)
big_jump = 1 + (int(sqrt((5 << w) // 21)) << 1)
total_jump = small_jump * big_jump
big_multiple = max(total_jump << 1, ((int(next_prime(prime)) - (total_jump >> 1)) // total_jump) * total_jump)
big_jump_2 = big_jump >> 1
small_jump_2 = small_jump >> 1
product = ONE
psmall_jump = multiply(p1, small_jump, n)
if not isinstance(psmall_jump, list):
return psmall_jump
ptotal_jump = multiply(psmall_jump, big_jump, n)
if not isinstance(ptotal_jump, list):
return ptotal_jump
pgiant_step = multiply(p1, big_multiple, n)
if not isinstance(pgiant_step, list):
return pgiant_step
small_multiples = [None]
for i in range(1, small_jump >> 1):
if gcd(i, small_jump) == 1:
tmp = multiply(p1, i, n)
if not isinstance(tmp, list):
return tmp
for i in range(len(tmp)):
tmp[i] = tmp[i][0]
small_multiples.append(tuple(tmp))
else:
small_multiples.append(None)
small_multiples = tuple(small_multiples)
big_multiples = [None]
for i in range(1, (big_jump + 1) >> 1):
tmp = multiply(psmall_jump, i, n)
if not isinstance(tmp, list):
return tmp
big_multiples.append(to_tuple(tmp))
big_multiples = tuple(big_multiples)
psmall_jump = to_tuple(psmall_jump)
ptotal_jump = to_tuple(ptotal_jump)
while big_multiple < u2:
big_multiple += total_jump
center_up = big_multiple
center_down = big_multiple
pgiant_step = add(ptotal_jump, pgiant_step, n)
if not isinstance(pgiant_step, list):
return pgiant_step
prime_up = next_prime(big_multiple - small_jump_2)
while prime_up < big_multiple + small_jump_2:
s = small_multiples[abs(int(prime_up) - big_multiple)]
for j in range(ncurves):
product *= pgiant_step[j][0] - s[j]
product %= n
prime_up = next_prime(prime_up)
for i in range(1, big_jump_2 + 1):
center_up += small_jump
center_down -= small_jump
pmed_step_up, pmed_step_down = add_sub_x_only(big_multiples[i], pgiant_step, n)
if pmed_step_down == None:
return pmed_step_up
while prime_up < center_up + small_jump_2:
s = small_multiples[abs(int(prime_up) - center_up)]
for j in range(ncurves):
product *= pmed_step_up[j] - s[j]
product %= n
prime_up = next_prime(prime_up)
prime_down = next_prime(center_down - small_jump_2)
while prime_down < center_down + small_jump_2:
s = small_multiples[abs(int(prime_down) - center_down)]
for j in range(ncurves):
product *= pmed_step_down[j] - s[j]
product %= n
prime_down = next_prime(prime_down)
if gcd(product, n) != 1:
return gcd(product, n)
return 1
def fast_multiply(p, d, n, w):
'''Multiplies each element of p by d. Multiplication is on