/
factor_.py
2668 lines (2121 loc) · 76.2 KB
/
factor_.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
"""
Integer factorization
"""
from collections import defaultdict
import math
from sympy.core.containers import Dict
from sympy.core.mul import Mul
from sympy.core.numbers import Rational, Integer
from sympy.core.intfunc import num_digits
from sympy.core.power import Pow
from sympy.core.random import _randint
from sympy.core.singleton import S
from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
sqrtrem, iroot, bit_scan1, remove)
from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
from .generate import sieve, primerange, nextprime
from .digits import digits
from sympy.utilities.decorator import deprecated
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import as_int, filldedent
from .ecm import _ecm_one_factor
def smoothness(n):
"""
Return the B-smooth and B-power smooth values of n.
The smoothness of n is the largest prime factor of n; the power-
smoothness is the largest divisor raised to its multiplicity.
Examples
========
>>> from sympy.ntheory.factor_ import smoothness
>>> smoothness(2**7*3**2)
(3, 128)
>>> smoothness(2**4*13)
(13, 16)
>>> smoothness(2)
(2, 2)
See Also
========
factorint, smoothness_p
"""
if n == 1:
return (1, 1) # not prime, but otherwise this causes headaches
facs = factorint(n)
return max(facs), max(m**facs[m] for m in facs)
def smoothness_p(n, m=-1, power=0, visual=None):
"""
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
where:
1. p**M is the base-p divisor of n
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
3. psm(p + m) is the power smoothness of p + m
The list is sorted according to smoothness (default) or by power smoothness
if power=1.
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
factor govern the results that are obtained from the p +/- 1 type factoring
methods.
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> smoothness_p(10431, m=1)
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
>>> smoothness_p(10431)
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
>>> smoothness_p(10431, power=1)
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
If visual=True then an annotated string will be returned:
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
This string can also be generated directly from a factorization dictionary
and vice versa:
>>> factorint(17*9)
{3: 2, 17: 1}
>>> smoothness_p(_)
'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
>>> smoothness_p(_)
{3: 2, 17: 1}
The table of the output logic is:
====== ====== ======= =======
| Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict str tuple str
str str tuple dict
tuple str tuple str
n str tuple tuple
mul str tuple tuple
====== ====== ======= =======
See Also
========
factorint, smoothness
"""
# visual must be True, False or other (stored as None)
if visual in (1, 0):
visual = bool(visual)
elif visual not in (True, False):
visual = None
if isinstance(n, str):
if visual:
return n
d = {}
for li in n.splitlines():
k, v = [int(i) for i in
li.split('has')[0].split('=')[1].split('**')]
d[k] = v
if visual is not True and visual is not False:
return d
return smoothness_p(d, visual=False)
elif not isinstance(n, tuple):
facs = factorint(n, visual=False)
if power:
k = -1
else:
k = 1
if isinstance(n, tuple):
rv = n
else:
rv = (m, sorted([(f,
tuple([M] + list(smoothness(f + m))))
for f, M in list(facs.items())],
key=lambda x: (x[1][k], x[0])))
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
return rv
lines = []
for dat in rv[1]:
dat = flatten(dat)
dat.insert(2, m)
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
return '\n'.join(lines)
def multiplicity(p, n):
"""
Find the greatest integer m such that p**m divides n.
Examples
========
>>> from sympy import multiplicity, Rational
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
[0, 1, 2, 3, 3]
>>> multiplicity(3, Rational(1, 9))
-2
Note: when checking for the multiplicity of a number in a
large factorial it is most efficient to send it as an unevaluated
factorial or to call ``multiplicity_in_factorial`` directly:
>>> from sympy.ntheory import multiplicity_in_factorial
>>> from sympy import factorial
>>> p = factorial(25)
>>> n = 2**100
>>> nfac = factorial(n, evaluate=False)
>>> multiplicity(p, nfac)
52818775009509558395695966887
>>> _ == multiplicity_in_factorial(p, n)
True
See Also
========
trailing
"""
try:
p, n = as_int(p), as_int(n)
except ValueError:
from sympy.functions.combinatorial.factorials import factorial
if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
p = Rational(p)
n = Rational(n)
if p.q == 1:
if n.p == 1:
return -multiplicity(p.p, n.q)
return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
elif p.p == 1:
return multiplicity(p.q, n.q)
else:
like = min(
multiplicity(p.p, n.p),
multiplicity(p.q, n.q))
cross = min(
multiplicity(p.q, n.p),
multiplicity(p.p, n.q))
return like - cross
elif (isinstance(p, (SYMPY_INTS, Integer)) and
isinstance(n, factorial) and
isinstance(n.args[0], Integer) and
n.args[0] >= 0):
return multiplicity_in_factorial(p, n.args[0])
raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
if n == 0:
raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
return remove(n, p)[1]
def multiplicity_in_factorial(p, n):
"""return the largest integer ``m`` such that ``p**m`` divides ``n!``
without calculating the factorial of ``n``.
Parameters
==========
p : Integer
positive integer
n : Integer
non-negative integer
Examples
========
>>> from sympy.ntheory import multiplicity_in_factorial
>>> from sympy import factorial
>>> multiplicity_in_factorial(2, 3)
1
An instructive use of this is to tell how many trailing zeros
a given factorial has. For example, there are 6 in 25!:
>>> factorial(25)
15511210043330985984000000
>>> multiplicity_in_factorial(10, 25)
6
For large factorials, it is much faster/feasible to use
this function rather than computing the actual factorial:
>>> multiplicity_in_factorial(factorial(25), 2**100)
52818775009509558395695966887
See Also
========
multiplicity
"""
p, n = as_int(p), as_int(n)
if p <= 0:
raise ValueError('expecting positive integer got %s' % p )
if n < 0:
raise ValueError('expecting non-negative integer got %s' % n )
# keep only the largest of a given multiplicity since those
# of a given multiplicity will be goverened by the behavior
# of the largest factor
f = defaultdict(int)
for k, v in factorint(p).items():
f[v] = max(k, f[v])
# multiplicity of p in n! depends on multiplicity
# of prime `k` in p, so we floor divide by `v`
# and keep it if smaller than the multiplicity of p
# seen so far
return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
def _perfect_power(n, next_p=2):
""" Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
Explanation
===========
This is a low-level helper for ``perfect_power``, for internal use.
Parameters
==========
n : int
assume that n is a nonnegative integer
next_p : int
Assume that n has no factor less than next_p.
i.e., all(n % p for p in range(2, next_p)) is True
Examples
========
>>> from sympy.ntheory.factor_ import _perfect_power
>>> _perfect_power(16)
(2, 4)
>>> _perfect_power(17)
False
"""
if n <= 3:
return False
factors = {}
g = 0
multi = 1
def done(n, factors, g, multi):
g = gcd(g, multi)
if g == 1:
return False
factors[n] = multi
return math.prod(p**(e//g) for p, e in factors.items()), g
# If n is small, only trial factoring is faster
if n <= 1_000_000:
n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
if n > 1:
return False
g = gcd(*factors.values())
if g == 1:
return False
return math.prod(p**(e//g) for p, e in factors.items()), g
# divide by 2
if next_p < 3:
g = bit_scan1(n)
if g:
if g == 1:
return False
n >>= g
factors[2] = g
if n == 1:
return 2, g
else:
# If `m**g`, then we have found perfect power.
# Otherwise, there is no possibility of perfect power, especially if `g` is prime.
m, _exact = iroot(n, g)
if _exact:
return 2*m, g
elif isprime(g):
return False
next_p = 3
# square number?
while n & 7 == 1: # n % 8 == 1:
m, _exact = iroot(n, 2)
if _exact:
n = m
multi <<= 1
else:
break
if n < next_p**3:
return done(n, factors, g, multi)
# trial factoring
# Since the maximum value an exponent can take is `log_{next_p}(n)`,
# the number of exponents to be checked can be reduced by performing a trial factoring.
# The value of `tf_max` needs more consideration.
tf_max = n.bit_length()//27 + 24
if next_p < tf_max:
for p in primerange(next_p, tf_max):
m, t = remove(n, p)
if t:
n = m
t *= multi
_g = gcd(g, t)
if _g == 1:
return False
factors[p] = t
if n == 1:
return math.prod(p**(e//_g)
for p, e in factors.items()), _g
elif g == 0 or _g < g: # If g is updated
g = _g
m, _exact = iroot(n**multi, g)
if _exact:
return m * math.prod(p**(e//g)
for p, e in factors.items()), g
elif isprime(g):
return False
next_p = tf_max
if n < next_p**3:
return done(n, factors, g, multi)
# check iroot
if g:
# If g is non-zero, the exponent is a divisor of g.
# 2 can be omitted since it has already been checked.
prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
else:
# The maximum possible value of the exponent is `log_{next_p}(n)`.
# To compensate for the presence of computational error, 2 is added.
prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
logn = math.log2(n)
threshold = logn / 40 # Threshold for direct calculation
for p in prime_iter:
if threshold < p:
# If p is large, find the power root p directly without `iroot`.
while True:
b = pow(2, logn / p)
rb = int(b + 0.5)
if abs(rb - b) < 0.01 and rb**p == n:
n = rb
multi *= p
logn = math.log2(n)
else:
break
else:
while True:
m, _exact = iroot(n, p)
if _exact:
n = m
multi *= p
logn = math.log2(n)
else:
break
if n < next_p**(p + 2):
break
return done(n, factors, g, multi)
def perfect_power(n, candidates=None, big=True, factor=True):
"""
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
perfect power). A ValueError is raised if ``n`` is not Rational.
By default, the base is recursively decomposed and the exponents
collected so the largest possible ``e`` is sought. If ``big=False``
then the smallest possible ``e`` (thus prime) will be chosen.
If ``factor=True`` then simultaneous factorization of ``n`` is
attempted since finding a factor indicates the only possible root
for ``n``. This is True by default since only a few small factors will
be tested in the course of searching for the perfect power.
The use of ``candidates`` is primarily for internal use; if provided,
False will be returned if ``n`` cannot be written as a power with one
of the candidates as an exponent and factoring (beyond testing for
a factor of 2) will not be attempted.
Examples
========
>>> from sympy import perfect_power, Rational
>>> perfect_power(16)
(2, 4)
>>> perfect_power(16, big=False)
(4, 2)
Negative numbers can only have odd perfect powers:
>>> perfect_power(-4)
False
>>> perfect_power(-8)
(-2, 3)
Rationals are also recognized:
>>> perfect_power(Rational(1, 2)**3)
(1/2, 3)
>>> perfect_power(Rational(-3, 2)**3)
(-3/2, 3)
Notes
=====
To know whether an integer is a perfect power of 2 use
>>> is2pow = lambda n: bool(n and not n & (n - 1))
>>> [(i, is2pow(i)) for i in range(5)]
[(0, False), (1, True), (2, True), (3, False), (4, True)]
It is not necessary to provide ``candidates``. When provided
it will be assumed that they are ints. The first one that is
larger than the computed maximum possible exponent will signal
failure for the routine.
>>> perfect_power(3**8, [9])
False
>>> perfect_power(3**8, [2, 4, 8])
(3, 8)
>>> perfect_power(3**8, [4, 8], big=False)
(9, 4)
See Also
========
sympy.core.intfunc.integer_nthroot
sympy.ntheory.primetest.is_square
"""
if isinstance(n, Rational) and not n.is_Integer:
p, q = n.as_numer_denom()
if p is S.One:
pp = perfect_power(q)
if pp:
pp = (n.func(1, pp[0]), pp[1])
else:
pp = perfect_power(p)
if pp:
num, e = pp
pq = perfect_power(q, [e])
if pq:
den, _ = pq
pp = n.func(num, den), e
return pp
n = as_int(n)
if n < 0:
pp = perfect_power(-n)
if pp:
b, e = pp
if e % 2:
return -b, e
return False
if candidates is None and big:
return _perfect_power(n)
if n <= 3:
# no unique exponent for 0, 1
# 2 and 3 have exponents of 1
return False
logn = math.log2(n)
max_possible = int(logn) + 2 # only check values less than this
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
min_possible = 2 + not_square
if not candidates:
candidates = primerange(min_possible, max_possible)
else:
candidates = sorted([i for i in candidates
if min_possible <= i < max_possible])
if n%2 == 0:
e = bit_scan1(n)
candidates = [i for i in candidates if e%i == 0]
if big:
candidates = reversed(candidates)
for e in candidates:
r, ok = iroot(n, e)
if ok:
return int(r), e
return False
def _factors():
rv = 2 + n % 2
while True:
yield rv
rv = nextprime(rv)
for fac, e in zip(_factors(), candidates):
# see if there is a factor present
if factor and n % fac == 0:
# find what the potential power is
e = remove(n, fac)[1]
# if it's a trivial power we are done
if e == 1:
return False
# maybe the e-th root of n is exact
r, exact = iroot(n, e)
if not exact:
# Having a factor, we know that e is the maximal
# possible value for a root of n.
# If n = fac**e*m can be written as a perfect
# power then see if m can be written as r**E where
# gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
m = n//fac**e
rE = perfect_power(m, candidates=divisors(e, generator=True))
if not rE:
return False
else:
r, E = rE
r, e = fac**(e//E)*r, E
if not big:
e0 = primefactors(e)
if e0[0] != e:
r, e = r**(e//e0[0]), e0[0]
return int(r), e
# Weed out downright impossible candidates
if logn/e < 40:
b = 2.0**(logn/e)
if abs(int(b + 0.5) - b) > 0.01:
continue
# now see if the plausible e makes a perfect power
r, exact = iroot(n, e)
if exact:
if big:
m = perfect_power(r, big=big, factor=factor)
if m:
r, e = m[0], e*m[1]
return int(r), e
return False
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
r"""
Use Pollard's rho method to try to extract a nontrivial factor
of ``n``. The returned factor may be a composite number. If no
factor is found, ``None`` is returned.
The algorithm generates pseudo-random values of x with a generator
function, replacing x with F(x). If F is not supplied then the
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
supplied; the ``a`` will be ignored if F was supplied.
The sequence of numbers generated by such functions generally have a
a lead-up to some number and then loop around back to that number and
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
For a given function, very different leader-loop values can be obtained
so it is a good idea to allow for retries:
>>> from sympy.ntheory.generate import cycle_length
>>> n = 16843009
>>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
>>> for s in range(5):
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
...
loop length = 2489; leader length = 43
loop length = 78; leader length = 121
loop length = 1482; leader length = 100
loop length = 1482; leader length = 286
loop length = 1482; leader length = 101
Here is an explicit example where there is a three element leadup to
a sequence of 3 numbers (11, 14, 4) that then repeat:
>>> x=2
>>> for i in range(9):
... print(x)
... x=(x**2+12)%17
...
2
16
13
11
14
4
11
14
4
>>> next(cycle_length(lambda x: (x**2+12)%17, 2))
(3, 3)
>>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
[2, 16, 13, 11, 14, 4]
Instead of checking the differences of all generated values for a gcd
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
traversed. Loops may be many thousands of steps long before rho finds a
factor or reports failure. If ``max_steps`` is specified, the iteration
is cancelled with a failure after the specified number of steps.
Examples
========
>>> from sympy import pollard_rho
>>> n=16843009
>>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
>>> pollard_rho(n, F=F)
257
Use the default setting with a bad value of ``a`` and no retries:
>>> pollard_rho(n, a=n-2, retries=0)
If retries is > 0 then perhaps the problem will correct itself when
new values are generated for a:
>>> pollard_rho(n, a=n-2, retries=1)
257
References
==========
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 229-231
"""
n = int(n)
if n < 5:
raise ValueError('pollard_rho should receive n > 4')
randint = _randint(seed + retries)
V = s
for i in range(retries + 1):
U = V
if not F:
F = lambda x: (pow(x, 2, n) + a) % n
j = 0
while 1:
if max_steps and (j > max_steps):
break
j += 1
U = F(U)
V = F(F(V)) # V is 2x further along than U
g = gcd(U - V, n)
if g == 1:
continue
if g == n:
break
return int(g)
V = randint(0, n - 1)
a = randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
F = None
return None
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
"""
Use Pollard's p-1 method to try to extract a nontrivial factor
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
The default is 2. If ``retries`` > 0 then if no factor is found after the
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
and the process repeated.
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
A search is made for factors next to even numbers having a power smoothness
less than ``B``. Choosing a larger B increases the likelihood of finding a
larger factor but takes longer. Whether a factor of n is found or not
depends on ``a`` and the power smoothness of the even number just less than
the factor p (hence the name p - 1).
Although some discussion of what constitutes a good ``a`` some
descriptions are hard to interpret. At the modular.math site referenced
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
for every prime power divisor of N. But consider the following:
>>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
>>> n=257*1009
>>> smoothness_p(n)
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
So we should (and can) find a root with B=16:
>>> pollard_pm1(n, B=16, a=3)
1009
If we attempt to increase B to 256 we find that it does not work:
>>> pollard_pm1(n, B=256)
>>>
But if the value of ``a`` is changed we find that only multiples of
257 work, e.g.:
>>> pollard_pm1(n, B=256, a=257)
1009
Checking different ``a`` values shows that all the ones that did not
work had a gcd value not equal to ``n`` but equal to one of the
factors:
>>> from sympy import ilcm, igcd, factorint, Pow
>>> M = 1
>>> for i in range(2, 256):
... M = ilcm(M, i)
...
>>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
... igcd(pow(a, M, n) - 1, n) != n])
{1009}
But does aM % d for every divisor of n give 1?
>>> aM = pow(255, M, n)
>>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
[(257**1, 1), (1009**1, 1)]
No, only one of them. So perhaps the principle is that a root will
be found for a given value of B provided that:
1) the power smoothness of the p - 1 value next to the root
does not exceed B
2) a**M % p != 1 for any of the divisors of n.
By trying more than one ``a`` it is possible that one of them
will yield a factor.
Examples
========
With the default smoothness bound, this number cannot be cracked:
>>> from sympy.ntheory import pollard_pm1
>>> pollard_pm1(21477639576571)
Increasing the smoothness bound helps:
>>> pollard_pm1(21477639576571, B=2000)
4410317
Looking at the smoothness of the factors of this number we find:
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
The B and B-pow are the same for the p - 1 factorizations of the divisors
because those factorizations had a very large prime factor:
>>> factorint(4410317 - 1)
{2: 2, 617: 1, 1787: 1}
>>> factorint(4869863-1)
{2: 1, 2434931: 1}
Note that until B reaches the B-pow value of 1787, the number is not cracked;
>>> pollard_pm1(21477639576571, B=1786)
>>> pollard_pm1(21477639576571, B=1787)
4410317
The B value has to do with the factors of the number next to the divisor,
not the divisors themselves. A worst case scenario is that the number next
to the factor p has a large prime divisisor or is a perfect power. If these
conditions apply then the power-smoothness will be about p/2 or p. The more
realistic is that there will be a large prime factor next to p requiring
a B value on the order of p/2. Although primes may have been searched for
up to this level, the p/2 is a factor of p - 1, something that we do not
know. The modular.math reference below states that 15% of numbers in the
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
percentages are nearly reversed...but in that range the simple trial
division is quite fast.
References
==========
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 236-238
.. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
.. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
"""
n = int(n)
if n < 4 or B < 3:
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
randint = _randint(seed + B)
# computing a**lcm(1,2,3,..B) % n for B > 2
# it looks weird, but it's right: primes run [2, B]
# and the answer's not right until the loop is done.
for i in range(retries + 1):
aM = a
for p in sieve.primerange(2, B + 1):
e = int(math.log(B, p))
aM = pow(aM, pow(p, e), n)
g = gcd(aM - 1, n)
if 1 < g < n:
return int(g)
# get a new a:
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
# give a zero, too, so we set the range as [2, n-2]. Some references
# say 'a' should be coprime to n, but either will detect factors.
a = randint(2, n - 2)
def _trial(factors, n, candidates, verbose=False):
"""
Helper function for integer factorization. Trial factors ``n`
against all integers given in the sequence ``candidates``
and updates the dict ``factors`` in-place. Returns the reduced
value of ``n`` and a flag indicating whether any factors were found.
"""
if verbose:
factors0 = list(factors.keys())
nfactors = len(factors)
for d in candidates:
if n % d == 0:
n, m = remove(n // d, d)
factors[d] = m + 1
if verbose:
for k in sorted(set(factors).difference(set(factors0))):
print(factor_msg % (k, factors[k]))
return int(n), len(factors) != nfactors
def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose, next_p):
"""
Helper function for integer factorization. Checks if ``n``
is a prime or a perfect power, and in those cases updates the factorization.
"""
if verbose:
print('Check for termination')
if n == 1:
if verbose:
print(complete_msg)
return True
if n < next_p**2 or isprime(n):
factors[int(n)] = 1
if verbose:
print(complete_msg)
return True
# since we've already been factoring there is no need to do
# simultaneous factoring with the power check
p = _perfect_power(n, next_p)
if not p:
return False
base, exp = p
if base < next_p**2 or isprime(base):
factors[base] = exp
else:
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
verbose=False)
for b, e in facs.items():
if verbose:
print(factor_msg % (b, e))
# int() can be removed when https://github.com/flintlib/python-flint/issues/92 is resolved
factors[b] = int(exp*e)
if verbose:
print(complete_msg)
return True
trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
trial_msg = "Trial division with primes [%i ... %i]"
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
factor_msg = '\t%i ** %i'
fermat_msg = 'Close factors satisying Fermat condition found.'
complete_msg = 'Factorization is complete.'
def _factorint_small(factors, n, limit, fail_max, next_p=2):
"""
Return the value of n and either a 0 (indicating that factorization up
to the limit was complete) or else the next near-prime that would have
been tested.
Factoring stops if there are fail_max unsuccessful tests in a row.
If factors of n were found they will be in the factors dictionary as
{factor: multiplicity} and the returned value of n will have had those
factors removed. The factors dictionary is modified in-place.
"""
def done(n, d):
"""return n, d if the sqrt(n) was not reached yet, else
n, 0 indicating that factoring is done.
"""
if d*d <= n:
return n, d
return n, 0
limit2 = limit**2
threshold2 = min(n, limit2)
if next_p < 3:
if not n & 1:
m = bit_scan1(n)
factors[2] = m
n >>= m
threshold2 = min(n, limit2)
next_p = 3
if threshold2 < 9: # next_p**2 = 9
return done(n, next_p)
if next_p < 5:
if not n % 3:
n //= 3
m = 1
while not n % 3:
n //= 3
m += 1
if m == 20:
n, mm = remove(n, 3)
m += mm
break
factors[3] = m
threshold2 = min(n, limit2)
next_p = 5
if threshold2 < 25: # next_p**2 = 25
return done(n, next_p)