FaustDerLegende commited on
Commit
09d3df6
·
verified ·
1 Parent(s): d002d3a

Upload folder using huggingface_hub (part 18)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +24 -0
  2. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/ecm.cpython-312.pyc +0 -0
  3. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-312.pyc +0 -0
  4. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-312.pyc +0 -0
  5. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/factor_.cpython-312.pyc +0 -0
  6. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/generate.cpython-312.pyc +0 -0
  7. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/modular.cpython-312.pyc +0 -0
  8. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-312.pyc +0 -0
  9. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-312.pyc +0 -0
  10. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/primetest.cpython-312.pyc +0 -0
  11. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/qs.cpython-312.pyc +0 -0
  12. .venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-312.pyc +0 -0
  13. .venv/lib/python3.12/site-packages/sympy/ntheory/bbp_pi.py +190 -0
  14. .venv/lib/python3.12/site-packages/sympy/ntheory/continued_fraction.py +369 -0
  15. .venv/lib/python3.12/site-packages/sympy/ntheory/digits.py +150 -0
  16. .venv/lib/python3.12/site-packages/sympy/ntheory/ecm.py +348 -0
  17. .venv/lib/python3.12/site-packages/sympy/ntheory/egyptian_fraction.py +223 -0
  18. .venv/lib/python3.12/site-packages/sympy/ntheory/elliptic_curve.py +397 -0
  19. .venv/lib/python3.12/site-packages/sympy/ntheory/factor_.py +2841 -0
  20. .venv/lib/python3.12/site-packages/sympy/ntheory/generate.py +1157 -0
  21. .venv/lib/python3.12/site-packages/sympy/ntheory/modular.py +291 -0
  22. .venv/lib/python3.12/site-packages/sympy/ntheory/multinomial.py +188 -0
  23. .venv/lib/python3.12/site-packages/sympy/ntheory/partitions_.py +277 -0
  24. .venv/lib/python3.12/site-packages/sympy/ntheory/primetest.py +830 -0
  25. .venv/lib/python3.12/site-packages/sympy/ntheory/qs.py +451 -0
  26. .venv/lib/python3.12/site-packages/sympy/ntheory/residue_ntheory.py +1963 -0
  27. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__init__.py +0 -0
  28. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-312.pyc +0 -0
  29. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-312.pyc +0 -0
  30. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-312.pyc +0 -0
  31. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-312.pyc +0 -0
  32. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-312.pyc +0 -0
  33. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-312.pyc +0 -0
  34. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-312.pyc +0 -0
  35. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-312.pyc +0 -0
  36. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-312.pyc +0 -0
  37. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_hypothesis.cpython-312.pyc +0 -0
  38. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-312.pyc +0 -0
  39. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-312.pyc +0 -0
  40. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-312.pyc +0 -0
  42. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_bbp_pi.py +134 -0
  45. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_continued_fraction.py +77 -0
  46. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_digits.py +55 -0
  47. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_ecm.py +63 -0
  48. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py +49 -0
  49. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_elliptic_curve.py +20 -0
  50. .venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_factor_.py +702 -0
.gitattributes CHANGED
@@ -443,3 +443,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
443
  .venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
444
  .venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
445
  .venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  .venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
444
  .venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
445
  .venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
446
+ .venv/lib/python3.12/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
447
+ .venv/lib/python3.12/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevparser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
448
+ .venv/lib/python3.12/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
449
+ .venv/lib/python3.12/site-packages/sympy/parsing/tests/__pycache__/test_c_parser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
450
+ .venv/lib/python3.12/site-packages/sympy/physics/__pycache__/secondquant.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
451
+ .venv/lib/python3.12/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_curve.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
452
+ .venv/lib/python3.12/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
453
+ .venv/lib/python3.12/site-packages/sympy/physics/control/__pycache__/lti.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
454
+ .venv/lib/python3.12/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
455
+ .venv/lib/python3.12/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
456
+ .venv/lib/python3.12/site-packages/sympy/physics/quantum/__pycache__/spin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
457
+ .venv/lib/python3.12/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
458
+ .venv/lib/python3.12/site-packages/sympy/plotting/__pycache__/series.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
459
+ .venv/lib/python3.12/site-packages/sympy/plotting/tests/__pycache__/test_series.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
460
+ .venv/lib/python3.12/site-packages/sympy/polys/__pycache__/compatibility.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
461
+ .venv/lib/python3.12/site-packages/sympy/polys/__pycache__/polyclasses.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
462
+ .venv/lib/python3.12/site-packages/sympy/polys/__pycache__/polyquinticconst.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
463
+ .venv/lib/python3.12/site-packages/sympy/polys/__pycache__/polytools.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
464
+ .venv/lib/python3.12/site-packages/sympy/polys/__pycache__/rings.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
465
+ .venv/lib/python3.12/site-packages/sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
466
+ .venv/lib/python3.12/site-packages/sympy/polys/domains/tests/__pycache__/test_domains.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
467
+ .venv/lib/python3.12/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
468
+ .venv/lib/python3.12/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainmatrix.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
469
+ .venv/lib/python3.12/site-packages/sympy/polys/numberfields/__pycache__/resolvent_lookup.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/ecm.cpython-312.pyc ADDED
Binary file (14 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-312.pyc ADDED
Binary file (8.47 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-312.pyc ADDED
Binary file (19.3 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/factor_.cpython-312.pyc ADDED
Binary file (92.4 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/generate.cpython-312.pyc ADDED
Binary file (39.1 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/modular.cpython-312.pyc ADDED
Binary file (9.41 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-312.pyc ADDED
Binary file (6.07 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-312.pyc ADDED
Binary file (11.8 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/primetest.cpython-312.pyc ADDED
Binary file (23.8 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/qs.cpython-312.pyc ADDED
Binary file (18 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-312.pyc ADDED
Binary file (61.5 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/bbp_pi.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This implementation is a heavily modified fixed point implementation of
3
+ BBP_formula for calculating the nth position of pi. The original hosted
4
+ at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
5
+
6
+ # Permission is hereby granted, free of charge, to any person obtaining
7
+ # a copy of this software and associated documentation files (the
8
+ # "Software"), to deal in the Software without restriction, including
9
+ # without limitation the rights to use, copy, modify, merge, publish,
10
+ # distribute, sub-license, and/or sell copies of the Software, and to
11
+ # permit persons to whom the Software is furnished to do so, subject to
12
+ # the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be
15
+ # included in all copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
+ # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
+ # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
+ # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
+ # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ Modifications:
26
+
27
+ 1.Once the nth digit and desired number of digits is selected, the
28
+ number of digits of working precision is calculated to ensure that
29
+ the hexadecimal digits returned are accurate. This is calculated as
30
+
31
+ int(math.log(start + prec)/math.log(16) + prec + 3)
32
+ --------------------------------------- --------
33
+ / /
34
+ number of hex digits additional digits
35
+
36
+ This was checked by the following code which completed without
37
+ errors (and dig are the digits included in the test_bbp.py file):
38
+
39
+ for i in range(0,1000):
40
+ for j in range(1,1000):
41
+ a, b = pi_hex_digits(i, j), dig[i:i+j]
42
+ if a != b:
43
+ print('%s\n%s'%(a,b))
44
+
45
+ Deceasing the additional digits by 1 generated errors, so '3' is
46
+ the smallest additional precision needed to calculate the above
47
+ loop without errors. The following trailing 10 digits were also
48
+ checked to be accurate (and the times were slightly faster with
49
+ some of the constant modifications that were made):
50
+
51
+ >> from time import time
52
+ >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
53
+ ('e90c6cc0ac', 0.0)
54
+ >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
55
+ ('26aab49ec6', 0.17100000381469727)
56
+ >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
57
+ ('a22673c1a5', 4.7109999656677246)
58
+ >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
59
+ ('9ffd342362', 59.985999822616577)
60
+ >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
61
+ ('c1a42e06a1', 689.51800012588501)
62
+
63
+ 2. The while loop to evaluate whether the series has converged quits
64
+ when the addition amount `dt` has dropped to zero.
65
+
66
+ 3. the formatting string to convert the decimal to hexadecimal is
67
+ calculated for the given precision.
68
+
69
+ 4. pi_hex_digits(n) changed to have coefficient to the formula in an
70
+ array (perhaps just a matter of preference).
71
+
72
+ '''
73
+
74
+ from sympy.utilities.misc import as_int
75
+
76
+
77
+ def _series(j, n, prec=14):
78
+
79
+ # Left sum from the bbp algorithm
80
+ s = 0
81
+ D = _dn(n, prec)
82
+ D4 = 4 * D
83
+ d = j
84
+ for k in range(n + 1):
85
+ s += (pow(16, n - k, d) << D4) // d
86
+ d += 8
87
+
88
+ # Right sum iterates to infinity for full precision, but we
89
+ # stop at the point where one iteration is beyond the precision
90
+ # specified.
91
+
92
+ t = 0
93
+ k = n + 1
94
+ e = D4 - 4 # 4*(D + n - k)
95
+ d = 8 * k + j
96
+ while True:
97
+ dt = (1 << e) // d
98
+ if not dt:
99
+ break
100
+ t += dt
101
+ # k += 1
102
+ e -= 4
103
+ d += 8
104
+ total = s + t
105
+
106
+ return total
107
+
108
+
109
+ def pi_hex_digits(n, prec=14):
110
+ """Returns a string containing ``prec`` (default 14) digits
111
+ starting at the nth digit of pi in hex. Counting of digits
112
+ starts at 0 and the decimal is not counted, so for n = 0 the
113
+ returned value starts with 3; n = 1 corresponds to the first
114
+ digit past the decimal point (which in hex is 2).
115
+
116
+ Parameters
117
+ ==========
118
+
119
+ n : non-negative integer
120
+ prec : non-negative integer. default = 14
121
+
122
+ Returns
123
+ =======
124
+
125
+ str : Returns a string containing ``prec`` digits
126
+ starting at the nth digit of pi in hex.
127
+ If ``prec`` = 0, returns empty string.
128
+
129
+ Raises
130
+ ======
131
+
132
+ ValueError
133
+ If ``n`` < 0 or ``prec`` < 0.
134
+ Or ``n`` or ``prec`` is not an integer.
135
+
136
+ Examples
137
+ ========
138
+
139
+ >>> from sympy.ntheory.bbp_pi import pi_hex_digits
140
+ >>> pi_hex_digits(0)
141
+ '3243f6a8885a30'
142
+ >>> pi_hex_digits(0, 3)
143
+ '324'
144
+
145
+ These are consistent with the following results
146
+
147
+ >>> import math
148
+ >>> hex(int(math.pi * 2**((14-1)*4)))
149
+ '0x3243f6a8885a30'
150
+ >>> hex(int(math.pi * 2**((3-1)*4)))
151
+ '0x324'
152
+
153
+ References
154
+ ==========
155
+
156
+ .. [1] http://www.numberworld.org/digits/Pi/
157
+ """
158
+ n, prec = as_int(n), as_int(prec)
159
+ if n < 0:
160
+ raise ValueError('n cannot be negative')
161
+ if prec < 0:
162
+ raise ValueError('prec cannot be negative')
163
+ if prec == 0:
164
+ return ''
165
+
166
+ # main of implementation arrays holding formulae coefficients
167
+ n -= 1
168
+ a = [4, 2, 1, 1]
169
+ j = [1, 4, 5, 6]
170
+
171
+ #formulae
172
+ D = _dn(n, prec)
173
+ x = + (a[0]*_series(j[0], n, prec)
174
+ - a[1]*_series(j[1], n, prec)
175
+ - a[2]*_series(j[2], n, prec)
176
+ - a[3]*_series(j[3], n, prec)) & (16**D - 1)
177
+
178
+ s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
179
+ return s
180
+
181
+
182
+ def _dn(n, prec):
183
+ # controller for n dependence on precision
184
+ # n = starting digit index
185
+ # prec = the number of total digits to compute
186
+ n += 1 # because we subtract 1 for _series
187
+
188
+ # assert int(math.log(n + prec)/math.log(16)) ==\
189
+ # ((n + prec).bit_length() - 1) // 4
190
+ return ((n + prec).bit_length() - 1) // 4 + prec + 3
.venv/lib/python3.12/site-packages/sympy/ntheory/continued_fraction.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import itertools
3
+ from sympy.core.exprtools import factor_terms
4
+ from sympy.core.numbers import Integer, Rational
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import Dummy
7
+ from sympy.core.sympify import _sympify
8
+ from sympy.utilities.misc import as_int
9
+
10
+
11
+ def continued_fraction(a) -> list:
12
+ """Return the continued fraction representation of a Rational or
13
+ quadratic irrational.
14
+
15
+ Examples
16
+ ========
17
+
18
+ >>> from sympy.ntheory.continued_fraction import continued_fraction
19
+ >>> from sympy import sqrt
20
+ >>> continued_fraction((1 + 2*sqrt(3))/5)
21
+ [0, 1, [8, 3, 34, 3]]
22
+
23
+ See Also
24
+ ========
25
+ continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents
26
+ """
27
+ e = _sympify(a)
28
+ if all(i.is_Rational for i in e.atoms()):
29
+ if e.is_Integer:
30
+ return continued_fraction_periodic(e, 1, 0)
31
+ elif e.is_Rational:
32
+ return continued_fraction_periodic(e.p, e.q, 0)
33
+ elif e.is_Pow and e.exp is S.Half and e.base.is_Integer:
34
+ return continued_fraction_periodic(0, 1, e.base)
35
+ elif e.is_Mul and len(e.args) == 2 and (
36
+ e.args[0].is_Rational and
37
+ e.args[1].is_Pow and
38
+ e.args[1].base.is_Integer and
39
+ e.args[1].exp is S.Half):
40
+ a, b = e.args
41
+ return continued_fraction_periodic(0, a.q, b.base, a.p)
42
+ else:
43
+ # this should not have to work very hard- no
44
+ # simplification, cancel, etc... which should be
45
+ # done by the user. e.g. This is a fancy 1 but
46
+ # the user should simplify it first:
47
+ # sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2)
48
+ p, d = e.expand().as_numer_denom()
49
+ if d.is_Integer:
50
+ if p.is_Rational:
51
+ return continued_fraction_periodic(p, d)
52
+ # look for a + b*c
53
+ # with c = sqrt(s)
54
+ if p.is_Add and len(p.args) == 2:
55
+ a, bc = p.args
56
+ else:
57
+ a = S.Zero
58
+ bc = p
59
+ if a.is_Integer:
60
+ b = S.NaN
61
+ if bc.is_Mul and len(bc.args) == 2:
62
+ b, c = bc.args
63
+ elif bc.is_Pow:
64
+ b = Integer(1)
65
+ c = bc
66
+ if b.is_Integer and (
67
+ c.is_Pow and c.exp is S.Half and
68
+ c.base.is_Integer):
69
+ # (a + b*sqrt(c))/d
70
+ c = c.base
71
+ return continued_fraction_periodic(a, d, c, b)
72
+ raise ValueError(
73
+ 'expecting a rational or quadratic irrational, not %s' % e)
74
+
75
+
76
+ def continued_fraction_periodic(p, q, d=0, s=1) -> list:
77
+ r"""
78
+ Find the periodic continued fraction expansion of a quadratic irrational.
79
+
80
+ Compute the continued fraction expansion of a rational or a
81
+ quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where
82
+ `p`, `q \ne 0` and `d \ge 0` are integers.
83
+
84
+ Returns the continued fraction representation (canonical form) as
85
+ a list of integers, optionally ending (for quadratic irrationals)
86
+ with list of integers representing the repeating digits.
87
+
88
+ Parameters
89
+ ==========
90
+
91
+ p : int
92
+ the rational part of the number's numerator
93
+ q : int
94
+ the denominator of the number
95
+ d : int, optional
96
+ the irrational part (discriminator) of the number's numerator
97
+ s : int, optional
98
+ the coefficient of the irrational part
99
+
100
+ Examples
101
+ ========
102
+
103
+ >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
104
+ >>> continued_fraction_periodic(3, 2, 7)
105
+ [2, [1, 4, 1, 1]]
106
+
107
+ Golden ratio has the simplest continued fraction expansion:
108
+
109
+ >>> continued_fraction_periodic(1, 2, 5)
110
+ [[1]]
111
+
112
+ If the discriminator is zero or a perfect square then the number will be a
113
+ rational number:
114
+
115
+ >>> continued_fraction_periodic(4, 3, 0)
116
+ [1, 3]
117
+ >>> continued_fraction_periodic(4, 3, 49)
118
+ [3, 1, 2]
119
+
120
+ See Also
121
+ ========
122
+
123
+ continued_fraction_iterator, continued_fraction_reduce
124
+
125
+ References
126
+ ==========
127
+
128
+ .. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction
129
+ .. [2] K. Rosen. Elementary Number theory and its applications.
130
+ Addison-Wesley, 3 Sub edition, pages 379-381, January 1992.
131
+
132
+ """
133
+ from sympy.functions import sqrt, floor
134
+
135
+ p, q, d, s = list(map(as_int, [p, q, d, s]))
136
+
137
+ if d < 0:
138
+ raise ValueError("expected non-negative for `d` but got %s" % d)
139
+
140
+ if q == 0:
141
+ raise ValueError("The denominator cannot be 0.")
142
+
143
+ if not s:
144
+ d = 0
145
+
146
+ # check for rational case
147
+ sd = sqrt(d)
148
+ if sd.is_Integer:
149
+ return list(continued_fraction_iterator(Rational(p + s*sd, q)))
150
+
151
+ # irrational case with sd != Integer
152
+ if q < 0:
153
+ p, q, s = -p, -q, -s
154
+
155
+ n = (p + s*sd)/q
156
+ if n < 0:
157
+ w = floor(-n)
158
+ f = -n - w
159
+ one_f = continued_fraction(1 - f) # 1-f < 1 so cf is [0 ... [...]]
160
+ one_f[0] -= w + 1
161
+ return one_f
162
+
163
+ d *= s**2
164
+ sd *= s
165
+
166
+ if (d - p**2)%q:
167
+ d *= q**2
168
+ sd *= q
169
+ p *= q
170
+ q *= q
171
+
172
+ terms: list[int] = []
173
+ pq = {}
174
+
175
+ while (p, q) not in pq:
176
+ pq[(p, q)] = len(terms)
177
+ terms.append((p + sd)//q)
178
+ p = terms[-1]*q - p
179
+ q = (d - p**2)//q
180
+
181
+ i = pq[(p, q)]
182
+ return terms[:i] + [terms[i:]] # type: ignore
183
+
184
+
185
+ def continued_fraction_reduce(cf):
186
+ """
187
+ Reduce a continued fraction to a rational or quadratic irrational.
188
+
189
+ Compute the rational or quadratic irrational number from its
190
+ terminating or periodic continued fraction expansion. The
191
+ continued fraction expansion (cf) should be supplied as a
192
+ terminating iterator supplying the terms of the expansion. For
193
+ terminating continued fractions, this is equivalent to
194
+ ``list(continued_fraction_convergents(cf))[-1]``, only a little more
195
+ efficient. If the expansion has a repeating part, a list of the
196
+ repeating terms should be returned as the last element from the
197
+ iterator. This is the format returned by
198
+ continued_fraction_periodic.
199
+
200
+ For quadratic irrationals, returns the largest solution found,
201
+ which is generally the one sought, if the fraction is in canonical
202
+ form (all terms positive except possibly the first).
203
+
204
+ Examples
205
+ ========
206
+
207
+ >>> from sympy.ntheory.continued_fraction import continued_fraction_reduce
208
+ >>> continued_fraction_reduce([1, 2, 3, 4, 5])
209
+ 225/157
210
+ >>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2])
211
+ -256/233
212
+ >>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10)
213
+ 2.718281835
214
+ >>> continued_fraction_reduce([1, 4, 2, [3, 1]])
215
+ (sqrt(21) + 287)/238
216
+ >>> continued_fraction_reduce([[1]])
217
+ (1 + sqrt(5))/2
218
+ >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
219
+ >>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13))
220
+ (sqrt(13) + 8)/5
221
+
222
+ See Also
223
+ ========
224
+
225
+ continued_fraction_periodic
226
+
227
+ """
228
+ from sympy.solvers import solve
229
+
230
+ period = []
231
+ x = Dummy('x')
232
+
233
+ def untillist(cf):
234
+ for nxt in cf:
235
+ if isinstance(nxt, list):
236
+ period.extend(nxt)
237
+ yield x
238
+ break
239
+ yield nxt
240
+
241
+ a = S.Zero
242
+ for a in continued_fraction_convergents(untillist(cf)):
243
+ pass
244
+
245
+ if period:
246
+ y = Dummy('y')
247
+ solns = solve(continued_fraction_reduce(period + [y]) - y, y)
248
+ solns.sort()
249
+ pure = solns[-1]
250
+ rv = a.subs(x, pure).radsimp()
251
+ else:
252
+ rv = a
253
+ if rv.is_Add:
254
+ rv = factor_terms(rv)
255
+ if rv.is_Mul and rv.args[0] == -1:
256
+ rv = rv.func(*rv.args)
257
+ return rv
258
+
259
+
260
+ def continued_fraction_iterator(x):
261
+ """
262
+ Return continued fraction expansion of x as iterator.
263
+
264
+ Examples
265
+ ========
266
+
267
+ >>> from sympy import Rational, pi
268
+ >>> from sympy.ntheory.continued_fraction import continued_fraction_iterator
269
+
270
+ >>> list(continued_fraction_iterator(Rational(3, 8)))
271
+ [0, 2, 1, 2]
272
+ >>> list(continued_fraction_iterator(Rational(-3, 8)))
273
+ [-1, 1, 1, 1, 2]
274
+
275
+ >>> for i, v in enumerate(continued_fraction_iterator(pi)):
276
+ ... if i > 7:
277
+ ... break
278
+ ... print(v)
279
+ 3
280
+ 7
281
+ 15
282
+ 1
283
+ 292
284
+ 1
285
+ 1
286
+ 1
287
+
288
+ References
289
+ ==========
290
+
291
+ .. [1] https://en.wikipedia.org/wiki/Continued_fraction
292
+
293
+ """
294
+ from sympy.functions import floor
295
+ while True:
296
+ i = floor(x)
297
+ yield i
298
+ x -= i
299
+ if not x:
300
+ break
301
+ x = 1/x
302
+
303
+
304
+ def continued_fraction_convergents(cf):
305
+ """
306
+ Return an iterator over the convergents of a continued fraction (cf).
307
+
308
+ The parameter should be in either of the following to forms:
309
+ - A list of partial quotients, possibly with the last element being a list
310
+ of repeating partial quotients, such as might be returned by
311
+ continued_fraction and continued_fraction_periodic.
312
+ - An iterable returning successive partial quotients of the continued
313
+ fraction, such as might be returned by continued_fraction_iterator.
314
+
315
+ In computing the convergents, the continued fraction need not be strictly
316
+ in canonical form (all integers, all but the first positive).
317
+ Rational and negative elements may be present in the expansion.
318
+
319
+ Examples
320
+ ========
321
+
322
+ >>> from sympy.core import pi
323
+ >>> from sympy import S
324
+ >>> from sympy.ntheory.continued_fraction import \
325
+ continued_fraction_convergents, continued_fraction_iterator
326
+
327
+ >>> list(continued_fraction_convergents([0, 2, 1, 2]))
328
+ [0, 1/2, 1/3, 3/8]
329
+
330
+ >>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')]))
331
+ [1, 3, 19/5, 7]
332
+
333
+ >>> it = continued_fraction_convergents(continued_fraction_iterator(pi))
334
+ >>> for n in range(7):
335
+ ... print(next(it))
336
+ 3
337
+ 22/7
338
+ 333/106
339
+ 355/113
340
+ 103993/33102
341
+ 104348/33215
342
+ 208341/66317
343
+
344
+ >>> it = continued_fraction_convergents([1, [1, 2]]) # sqrt(3)
345
+ >>> for n in range(7):
346
+ ... print(next(it))
347
+ 1
348
+ 2
349
+ 5/3
350
+ 7/4
351
+ 19/11
352
+ 26/15
353
+ 71/41
354
+
355
+ See Also
356
+ ========
357
+
358
+ continued_fraction_iterator, continued_fraction, continued_fraction_periodic
359
+
360
+ """
361
+ if isinstance(cf, list) and isinstance(cf[-1], list):
362
+ cf = itertools.chain(cf[:-1], itertools.cycle(cf[-1]))
363
+ p_2, q_2 = S.Zero, S.One
364
+ p_1, q_1 = S.One, S.Zero
365
+ for a in cf:
366
+ p, q = a*p_1 + p_2, a*q_1 + q_2
367
+ p_2, q_2 = p_1, q_1
368
+ p_1, q_1 = p, q
369
+ yield p/q
.venv/lib/python3.12/site-packages/sympy/ntheory/digits.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
4
+ from sympy.utilities.misc import as_int
5
+
6
+
7
+ def digits(n, b=10, digits=None):
8
+ """
9
+ Return a list of the digits of ``n`` in base ``b``. The first
10
+ element in the list is ``b`` (or ``-b`` if ``n`` is negative).
11
+
12
+ Examples
13
+ ========
14
+
15
+ >>> from sympy.ntheory.digits import digits
16
+ >>> digits(35)
17
+ [10, 3, 5]
18
+
19
+ If the number is negative, the negative sign will be placed on the
20
+ base (which is the first element in the returned list):
21
+
22
+ >>> digits(-35)
23
+ [-10, 3, 5]
24
+
25
+ Bases other than 10 (and greater than 1) can be selected with ``b``:
26
+
27
+ >>> digits(27, b=2)
28
+ [2, 1, 1, 0, 1, 1]
29
+
30
+ Use the ``digits`` keyword if a certain number of digits is desired:
31
+
32
+ >>> digits(35, digits=4)
33
+ [10, 0, 0, 3, 5]
34
+
35
+ Parameters
36
+ ==========
37
+
38
+ n: integer
39
+ The number whose digits are returned.
40
+
41
+ b: integer
42
+ The base in which digits are computed.
43
+
44
+ digits: integer (or None for all digits)
45
+ The number of digits to be returned (padded with zeros, if
46
+ necessary).
47
+
48
+ See Also
49
+ ========
50
+ sympy.core.intfunc.num_digits, count_digits
51
+ """
52
+
53
+ b = as_int(b)
54
+ n = as_int(n)
55
+ if b < 2:
56
+ raise ValueError("b must be greater than 1")
57
+ else:
58
+ x, y = abs(n), []
59
+ while x >= b:
60
+ x, r = divmod(x, b)
61
+ y.append(r)
62
+ y.append(x)
63
+ y.append(-b if n < 0 else b)
64
+ y.reverse()
65
+ ndig = len(y) - 1
66
+ if digits is not None:
67
+ if ndig > digits:
68
+ raise ValueError(
69
+ "For %s, at least %s digits are needed." % (n, ndig))
70
+ elif ndig < digits:
71
+ y[1:1] = [0]*(digits - ndig)
72
+ return y
73
+
74
+
75
+ def count_digits(n, b=10):
76
+ """
77
+ Return a dictionary whose keys are the digits of ``n`` in the
78
+ given base, ``b``, with keys indicating the digits appearing in the
79
+ number and values indicating how many times that digit appeared.
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.ntheory import count_digits
85
+
86
+ >>> count_digits(1111339)
87
+ {1: 4, 3: 2, 9: 1}
88
+
89
+ The digits returned are always represented in base-10
90
+ but the number itself can be entered in any format that is
91
+ understood by Python; the base of the number can also be
92
+ given if it is different than 10:
93
+
94
+ >>> n = 0xFA; n
95
+ 250
96
+ >>> count_digits(_)
97
+ {0: 1, 2: 1, 5: 1}
98
+ >>> count_digits(n, 16)
99
+ {10: 1, 15: 1}
100
+
101
+ The default dictionary will return a 0 for any digit that did
102
+ not appear in the number. For example, which digits appear 7
103
+ times in ``77!``:
104
+
105
+ >>> from sympy import factorial
106
+ >>> c77 = count_digits(factorial(77))
107
+ >>> [i for i in range(10) if c77[i] == 7]
108
+ [1, 3, 7, 9]
109
+
110
+ See Also
111
+ ========
112
+ sympy.core.intfunc.num_digits, digits
113
+ """
114
+ rv = defaultdict(int, multiset(digits(n, b)).items())
115
+ rv.pop(b) if b in rv else rv.pop(-b) # b or -b is there
116
+ return rv
117
+
118
+
119
+ def is_palindromic(n, b=10):
120
+ """return True if ``n`` is the same when read from left to right
121
+ or right to left in the given base, ``b``.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy.ntheory import is_palindromic
127
+
128
+ >>> all(is_palindromic(i) for i in (-11, 1, 22, 121))
129
+ True
130
+
131
+ The second argument allows you to test numbers in other
132
+ bases. For example, 88 is palindromic in base-10 but not
133
+ in base-8:
134
+
135
+ >>> is_palindromic(88, 8)
136
+ False
137
+
138
+ On the other hand, a number can be palindromic in base-8 but
139
+ not in base-10:
140
+
141
+ >>> 0o121, is_palindromic(0o121)
142
+ (81, False)
143
+
144
+ Or it might be palindromic in both bases:
145
+
146
+ >>> oct(121), is_palindromic(121, 8) and is_palindromic(121)
147
+ ('0o171', True)
148
+
149
+ """
150
+ return _palindromic(digits(n, b), 1)
.venv/lib/python3.12/site-packages/sympy/ntheory/ecm.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import log
2
+
3
+ from sympy.core.random import _randint
4
+ from sympy.external.gmpy import gcd, invert, sqrt
5
+ from sympy.utilities.misc import as_int
6
+ from .generate import sieve, primerange
7
+ from .primetest import isprime
8
+
9
+
10
+ #----------------------------------------------------------------------------#
11
+ # #
12
+ # Lenstra's Elliptic Curve Factorization #
13
+ # #
14
+ #----------------------------------------------------------------------------#
15
+
16
+
17
+ class Point:
18
+ """Montgomery form of Points in an elliptic curve.
19
+ In this form, the addition and doubling of points
20
+ does not need any y-coordinate information thus
21
+ decreasing the number of operations.
22
+ Using Montgomery form we try to perform point addition
23
+ and doubling in least amount of multiplications.
24
+
25
+ The elliptic curve used here is of the form
26
+ (E : b*y**2*z = x**3 + a*x**2*z + x*z**2).
27
+ The a_24 parameter is equal to (a + 2)/4.
28
+
29
+ References
30
+ ==========
31
+
32
+ .. [1] Kris Gaj, Soonhak Kwon, Patrick Baier, Paul Kohlbrenner, Hoang Le, Mohammed Khaleeluddin, Ramakrishna Bachimanchi,
33
+ Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware,
34
+ Cryptographic Hardware and Embedded Systems - CHES 2006 (2006), pp. 119-133,
35
+ https://doi.org/10.1007/11894063_10
36
+ https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
37
+
38
+ """
39
+
40
+ def __init__(self, x_cord, z_cord, a_24, mod):
41
+ """
42
+ Initial parameters for the Point class.
43
+
44
+ Parameters
45
+ ==========
46
+
47
+ x_cord : X coordinate of the Point
48
+ z_cord : Z coordinate of the Point
49
+ a_24 : Parameter of the elliptic curve in Montgomery form
50
+ mod : modulus
51
+ """
52
+ self.x_cord = x_cord
53
+ self.z_cord = z_cord
54
+ self.a_24 = a_24
55
+ self.mod = mod
56
+
57
+ def __eq__(self, other):
58
+ """Two points are equal if X/Z of both points are equal
59
+ """
60
+ if self.a_24 != other.a_24 or self.mod != other.mod:
61
+ return False
62
+ return self.x_cord * other.z_cord % self.mod ==\
63
+ other.x_cord * self.z_cord % self.mod
64
+
65
+ def add(self, Q, diff):
66
+ """
67
+ Add two points self and Q where diff = self - Q. Moreover the assumption
68
+ is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm
69
+ requires 6 multiplications. Here the difference between the points
70
+ is already known and using this algorithm speeds up the addition
71
+ by reducing the number of multiplication required. Also in the
72
+ mont_ladder algorithm is constructed in a way so that the difference
73
+ between intermediate points is always equal to the initial point.
74
+ So, we always know what the difference between the point is.
75
+
76
+
77
+ Parameters
78
+ ==========
79
+
80
+ Q : point on the curve in Montgomery form
81
+ diff : self - Q
82
+
83
+ Examples
84
+ ========
85
+
86
+ >>> from sympy.ntheory.ecm import Point
87
+ >>> p1 = Point(11, 16, 7, 29)
88
+ >>> p2 = Point(13, 10, 7, 29)
89
+ >>> p3 = p2.add(p1, p1)
90
+ >>> p3.x_cord
91
+ 23
92
+ >>> p3.z_cord
93
+ 17
94
+ """
95
+ u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord)
96
+ v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord)
97
+ add, subt = u + v, u - v
98
+ x_cord = diff.z_cord * add * add % self.mod
99
+ z_cord = diff.x_cord * subt * subt % self.mod
100
+ return Point(x_cord, z_cord, self.a_24, self.mod)
101
+
102
+ def double(self):
103
+ """
104
+ Doubles a point in an elliptic curve in Montgomery form.
105
+ This algorithm requires 5 multiplications.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy.ntheory.ecm import Point
111
+ >>> p1 = Point(11, 16, 7, 29)
112
+ >>> p2 = p1.double()
113
+ >>> p2.x_cord
114
+ 13
115
+ >>> p2.z_cord
116
+ 10
117
+ """
118
+ u = pow(self.x_cord + self.z_cord, 2, self.mod)
119
+ v = pow(self.x_cord - self.z_cord, 2, self.mod)
120
+ diff = u - v
121
+ x_cord = u*v % self.mod
122
+ z_cord = diff*(v + self.a_24*diff) % self.mod
123
+ return Point(x_cord, z_cord, self.a_24, self.mod)
124
+
125
+ def mont_ladder(self, k):
126
+ """
127
+ Scalar multiplication of a point in Montgomery form
128
+ using Montgomery Ladder Algorithm.
129
+ A total of 11 multiplications are required in each step of this
130
+ algorithm.
131
+
132
+ Parameters
133
+ ==========
134
+
135
+ k : The positive integer multiplier
136
+
137
+ Examples
138
+ ========
139
+
140
+ >>> from sympy.ntheory.ecm import Point
141
+ >>> p1 = Point(11, 16, 7, 29)
142
+ >>> p3 = p1.mont_ladder(3)
143
+ >>> p3.x_cord
144
+ 23
145
+ >>> p3.z_cord
146
+ 17
147
+ """
148
+ Q = self
149
+ R = self.double()
150
+ for i in bin(k)[3:]:
151
+ if i == '1':
152
+ Q = R.add(Q, self)
153
+ R = R.double()
154
+ else:
155
+ R = Q.add(R, self)
156
+ Q = Q.double()
157
+ return Q
158
+
159
+
160
+ def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200, seed=None):
161
+ """Returns one factor of n using
162
+ Lenstra's 2 Stage Elliptic curve Factorization
163
+ with Suyama's Parameterization. Here Montgomery
164
+ arithmetic is used for fast computation of addition
165
+ and doubling of points in elliptic curve.
166
+
167
+ Explanation
168
+ ===========
169
+
170
+ This ECM method considers elliptic curves in Montgomery
171
+ form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves
172
+ elliptic curve operations (mod N), where the elements in
173
+ Z are reduced (mod N). Since N is not a prime, E over FF(N)
174
+ is not really an elliptic curve but we can still do point additions
175
+ and doubling as if FF(N) was a field.
176
+
177
+ Stage 1 : The basic algorithm involves taking a random point (P) on an
178
+ elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm.
179
+ Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|,
180
+ might be a smooth number that divides k. Then we have k = l * |E(FF(q))|
181
+ for some l. For any point belonging to the curve E, |E(FF(q))|*P = O,
182
+ hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn
183
+ factor of N (q) can be recovered by taking gcd(kP.z_cord, N).
184
+
185
+ Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize
186
+ the fact that even if kP != 0, the value of k might miss just one large
187
+ prime divisor of |E(FF(q))|. In this case we only need to compute the
188
+ scalar multiplication by p to get p*k*P = O. Here a second bound B2
189
+ restrict the size of possible values of p.
190
+
191
+ Parameters
192
+ ==========
193
+
194
+ n : Number to be Factored. Assume that it is a composite number.
195
+ B1 : Stage 1 Bound. Must be an even number.
196
+ B2 : Stage 2 Bound. Must be an even number.
197
+ max_curve : Maximum number of curves generated
198
+
199
+ Returns
200
+ =======
201
+
202
+ integer | None : a non-trivial divisor of ``n``. ``None`` if not found
203
+
204
+ References
205
+ ==========
206
+
207
+ .. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
208
+ 2nd Edition (2005), page 344, ISBN:978-0387252827
209
+ """
210
+ randint = _randint(seed)
211
+
212
+ # When calculating T, if (B1 - 2*D) is negative, it cannot be calculated.
213
+ D = min(sqrt(B2), B1 // 2 - 1)
214
+ sieve.extend(D)
215
+ beta = [0] * D
216
+ S = [0] * D
217
+ k = 1
218
+ for p in primerange(2, B1 + 1):
219
+ k *= pow(p, int(log(B1, p)))
220
+
221
+ # Pre-calculate the prime numbers to be used in stage 2.
222
+ # Using the fact that the x-coordinates of point P and its
223
+ # inverse -P coincide, the number of primes to be checked
224
+ # in stage 2 can be reduced.
225
+ deltas_list = []
226
+ for r in range(B1 + 2*D, B2 + 2*D, 4*D):
227
+ # d in deltas iff r+(2d+1) and/or r-(2d+1) is prime
228
+ deltas = {abs(q - r) >> 1 for q in primerange(r - 2*D, r + 2*D)}
229
+ deltas_list.append(list(deltas))
230
+
231
+ for _ in range(max_curve):
232
+ #Suyama's Parametrization
233
+ sigma = randint(6, n - 1)
234
+ u = (sigma**2 - 5) % n
235
+ v = (4*sigma) % n
236
+ u_3 = pow(u, 3, n)
237
+
238
+ try:
239
+ # We use the elliptic curve y**2 = x**3 + a*x**2 + x
240
+ # where a = pow(v - u, 3, n)*(3*u + v)*invert(4*u_3*v, n) - 2
241
+ # However, we do not declare a because it is more convenient
242
+ # to use a24 = (a + 2)*invert(4, n) in the calculation.
243
+ a24 = pow(v - u, 3, n)*(3*u + v)*invert(16*u_3*v, n) % n
244
+ except ZeroDivisionError:
245
+ #If the invert(16*u_3*v, n) doesn't exist (i.e., g != 1)
246
+ g = gcd(2*u_3*v, n)
247
+ #If g = n, try another curve
248
+ if g == n:
249
+ continue
250
+ return g
251
+
252
+ Q = Point(u_3, pow(v, 3, n), a24, n)
253
+ Q = Q.mont_ladder(k)
254
+ g = gcd(Q.z_cord, n)
255
+
256
+ #Stage 1 factor
257
+ if g != 1 and g != n:
258
+ return g
259
+ #Stage 1 failure. Q.z = 0, Try another curve
260
+ elif g == n:
261
+ continue
262
+
263
+ #Stage 2 - Improved Standard Continuation
264
+ S[0] = Q
265
+ Q2 = Q.double()
266
+ S[1] = Q2.add(Q, Q)
267
+ beta[0] = (S[0].x_cord*S[0].z_cord) % n
268
+ beta[1] = (S[1].x_cord*S[1].z_cord) % n
269
+ for d in range(2, D):
270
+ S[d] = S[d - 1].add(Q2, S[d - 2])
271
+ beta[d] = (S[d].x_cord*S[d].z_cord) % n
272
+ # i.e., S[i] = Q.mont_ladder(2*i + 1)
273
+
274
+ g = 1
275
+ W = Q.mont_ladder(4*D)
276
+ T = Q.mont_ladder(B1 - 2*D)
277
+ R = Q.mont_ladder(B1 + 2*D)
278
+ for deltas in deltas_list:
279
+ # R = Q.mont_ladder(r) where r in range(B1 + 2*D, B2 + 2*D, 4*D)
280
+ alpha = (R.x_cord*R.z_cord) % n
281
+ for delta in deltas:
282
+ # We want to calculate
283
+ # f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord
284
+ f = (R.x_cord - S[delta].x_cord)*\
285
+ (R.z_cord + S[delta].z_cord) - alpha + beta[delta]
286
+ g = (g*f) % n
287
+ T, R = R, R.add(W, T)
288
+ g = gcd(n, g)
289
+
290
+ #Stage 2 Factor found
291
+ if g != 1 and g != n:
292
+ return g
293
+
294
+
295
+ def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234):
296
+ """Performs factorization using Lenstra's Elliptic curve method.
297
+
298
+ This function repeatedly calls ``_ecm_one_factor`` to compute the factors
299
+ of n. First all the small factors are taken out using trial division.
300
+ Then ``_ecm_one_factor`` is used to compute one factor at a time.
301
+
302
+ Parameters
303
+ ==========
304
+
305
+ n : Number to be Factored
306
+ B1 : Stage 1 Bound. Must be an even number.
307
+ B2 : Stage 2 Bound. Must be an even number.
308
+ max_curve : Maximum number of curves generated
309
+ seed : Initialize pseudorandom generator
310
+
311
+ Examples
312
+ ========
313
+
314
+ >>> from sympy.ntheory import ecm
315
+ >>> ecm(25645121643901801)
316
+ {5394769, 4753701529}
317
+ >>> ecm(9804659461513846513)
318
+ {4641991, 2112166839943}
319
+ """
320
+ from .factor_ import _perfect_power
321
+ n = as_int(n)
322
+ if B1 % 2 != 0 or B2 % 2 != 0:
323
+ raise ValueError("both bounds must be even")
324
+ TF_LIMIT = 100000
325
+ factors = set()
326
+ for prime in sieve.primerange(2, TF_LIMIT):
327
+ if n % prime == 0:
328
+ factors.add(prime)
329
+ while(n % prime == 0):
330
+ n //= prime
331
+
332
+ queue = []
333
+ def check(m):
334
+ if isprime(m):
335
+ factors.add(m)
336
+ return
337
+ if result := _perfect_power(m, TF_LIMIT):
338
+ return check(result[0])
339
+ queue.append(m)
340
+ check(n)
341
+ while queue:
342
+ n = queue.pop()
343
+ factor = _ecm_one_factor(n, B1, B2, max_curve, seed)
344
+ if factor is None:
345
+ raise ValueError("Increase the bounds")
346
+ check(factor)
347
+ check(n // factor)
348
+ return factors
.venv/lib/python3.12/site-packages/sympy/ntheory/egyptian_fraction.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Tuple
2
+ from sympy.core.numbers import (Integer, Rational)
3
+ from sympy.core.singleton import S
4
+ import sympy.polys
5
+
6
+ from math import gcd
7
+
8
+
9
+ def egyptian_fraction(r, algorithm="Greedy"):
10
+ """
11
+ Return the list of denominators of an Egyptian fraction
12
+ expansion [1]_ of the said rational `r`.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ r : Rational or (p, q)
18
+ a positive rational number, ``p/q``.
19
+ algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional
20
+ Denotes the algorithm to be used (the default is "Greedy").
21
+
22
+ Examples
23
+ ========
24
+
25
+ >>> from sympy import Rational
26
+ >>> from sympy.ntheory.egyptian_fraction import egyptian_fraction
27
+ >>> egyptian_fraction(Rational(3, 7))
28
+ [3, 11, 231]
29
+ >>> egyptian_fraction((3, 7), "Graham Jewett")
30
+ [7, 8, 9, 56, 57, 72, 3192]
31
+ >>> egyptian_fraction((3, 7), "Takenouchi")
32
+ [4, 7, 28]
33
+ >>> egyptian_fraction((3, 7), "Golomb")
34
+ [3, 15, 35]
35
+ >>> egyptian_fraction((11, 5), "Golomb")
36
+ [1, 2, 3, 4, 9, 234, 1118, 2580]
37
+
38
+ See Also
39
+ ========
40
+
41
+ sympy.core.numbers.Rational
42
+
43
+ Notes
44
+ =====
45
+
46
+ Currently the following algorithms are supported:
47
+
48
+ 1) Greedy Algorithm
49
+
50
+ Also called the Fibonacci-Sylvester algorithm [2]_.
51
+ At each step, extract the largest unit fraction less
52
+ than the target and replace the target with the remainder.
53
+
54
+ It has some distinct properties:
55
+
56
+ a) Given `p/q` in lowest terms, generates an expansion of maximum
57
+ length `p`. Even as the numerators get large, the number of
58
+ terms is seldom more than a handful.
59
+
60
+ b) Uses minimal memory.
61
+
62
+ c) The terms can blow up (standard examples of this are 5/121 and
63
+ 31/311). The denominator is at most squared at each step
64
+ (doubly-exponential growth) and typically exhibits
65
+ singly-exponential growth.
66
+
67
+ 2) Graham Jewett Algorithm
68
+
69
+ The algorithm suggested by the result of Graham and Jewett.
70
+ Note that this has a tendency to blow up: the length of the
71
+ resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_.
72
+
73
+ 3) Takenouchi Algorithm
74
+
75
+ The algorithm suggested by Takenouchi (1921).
76
+ Differs from the Graham-Jewett algorithm only in the handling
77
+ of duplicates. See [3]_.
78
+
79
+ 4) Golomb's Algorithm
80
+
81
+ A method given by Golumb (1962), using modular arithmetic and
82
+ inverses. It yields the same results as a method using continued
83
+ fractions proposed by Bleicher (1972). See [4]_.
84
+
85
+ If the given rational is greater than or equal to 1, a greedy algorithm
86
+ of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking
87
+ all the unit fractions of this sequence until adding one more would be
88
+ greater than the given number. This list of denominators is prefixed
89
+ to the result from the requested algorithm used on the remainder. For
90
+ example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
91
+ 5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
92
+ 6, 7] is part of the harmonic sequence summing to 363/140, leaving a
93
+ remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
94
+ The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3,
95
+ 4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
96
+
97
+ References
98
+ ==========
99
+
100
+ .. [1] https://en.wikipedia.org/wiki/Egyptian_fraction
101
+ .. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
102
+ .. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html
103
+ .. [4] https://web.archive.org/web/20180413004012/https://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf
104
+
105
+ """
106
+
107
+ if not isinstance(r, Rational):
108
+ if isinstance(r, (Tuple, tuple)) and len(r) == 2:
109
+ r = Rational(*r)
110
+ else:
111
+ raise ValueError("Value must be a Rational or tuple of ints")
112
+ if r <= 0:
113
+ raise ValueError("Value must be positive")
114
+
115
+ # common cases that all methods agree on
116
+ x, y = r.as_numer_denom()
117
+ if y == 1 and x == 2:
118
+ return [Integer(i) for i in [1, 2, 3, 6]]
119
+ if x == y + 1:
120
+ return [S.One, y]
121
+
122
+ prefix, rem = egypt_harmonic(r)
123
+ if rem == 0:
124
+ return prefix
125
+ # work in Python ints
126
+ x, y = rem.p, rem.q
127
+ # assert x < y and gcd(x, y) = 1
128
+
129
+ if algorithm == "Greedy":
130
+ postfix = egypt_greedy(x, y)
131
+ elif algorithm == "Graham Jewett":
132
+ postfix = egypt_graham_jewett(x, y)
133
+ elif algorithm == "Takenouchi":
134
+ postfix = egypt_takenouchi(x, y)
135
+ elif algorithm == "Golomb":
136
+ postfix = egypt_golomb(x, y)
137
+ else:
138
+ raise ValueError("Entered invalid algorithm")
139
+ return prefix + [Integer(i) for i in postfix]
140
+
141
+
142
+ def egypt_greedy(x, y):
143
+ # assumes gcd(x, y) == 1
144
+ if x == 1:
145
+ return [y]
146
+ else:
147
+ a = (-y) % x
148
+ b = y*(y//x + 1)
149
+ c = gcd(a, b)
150
+ if c > 1:
151
+ num, denom = a//c, b//c
152
+ else:
153
+ num, denom = a, b
154
+ return [y//x + 1] + egypt_greedy(num, denom)
155
+
156
+
157
+ def egypt_graham_jewett(x, y):
158
+ # assumes gcd(x, y) == 1
159
+ l = [y] * x
160
+
161
+ # l is now a list of integers whose reciprocals sum to x/y.
162
+ # we shall now proceed to manipulate the elements of l without
163
+ # changing the reciprocated sum until all elements are unique.
164
+
165
+ while len(l) != len(set(l)):
166
+ l.sort() # so the list has duplicates. find a smallest pair
167
+ for i in range(len(l) - 1):
168
+ if l[i] == l[i + 1]:
169
+ break
170
+ # we have now identified a pair of identical
171
+ # elements: l[i] and l[i + 1].
172
+ # now comes the application of the result of graham and jewett:
173
+ l[i + 1] = l[i] + 1
174
+ # and we just iterate that until the list has no duplicates.
175
+ l.append(l[i]*(l[i] + 1))
176
+ return sorted(l)
177
+
178
+
179
+ def egypt_takenouchi(x, y):
180
+ # assumes gcd(x, y) == 1
181
+ # special cases for 3/y
182
+ if x == 3:
183
+ if y % 2 == 0:
184
+ return [y//2, y]
185
+ i = (y - 1)//2
186
+ j = i + 1
187
+ k = j + i
188
+ return [j, k, j*k]
189
+ l = [y] * x
190
+ while len(l) != len(set(l)):
191
+ l.sort()
192
+ for i in range(len(l) - 1):
193
+ if l[i] == l[i + 1]:
194
+ break
195
+ k = l[i]
196
+ if k % 2 == 0:
197
+ l[i] = l[i] // 2
198
+ del l[i + 1]
199
+ else:
200
+ l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2
201
+ return sorted(l)
202
+
203
+
204
+ def egypt_golomb(x, y):
205
+ # assumes x < y and gcd(x, y) == 1
206
+ if x == 1:
207
+ return [y]
208
+ xp = sympy.polys.ZZ.invert(int(x), int(y))
209
+ rv = [xp*y]
210
+ rv.extend(egypt_golomb((x*xp - 1)//y, xp))
211
+ return sorted(rv)
212
+
213
+
214
+ def egypt_harmonic(r):
215
+ # assumes r is Rational
216
+ rv = []
217
+ d = S.One
218
+ acc = S.Zero
219
+ while acc + 1/d <= r:
220
+ acc += 1/d
221
+ rv.append(d)
222
+ d += 1
223
+ return (rv, r - acc)
.venv/lib/python3.12/site-packages/sympy/ntheory/elliptic_curve.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import oo
2
+ from sympy.core.symbol import symbols
3
+ from sympy.polys.domains import FiniteField, QQ, RationalField, FF
4
+ from sympy.polys.polytools import Poly
5
+ from sympy.solvers.solvers import solve
6
+ from sympy.utilities.iterables import is_sequence
7
+ from sympy.utilities.misc import as_int
8
+ from .factor_ import divisors
9
+ from .residue_ntheory import polynomial_congruence
10
+
11
+
12
+ class EllipticCurve:
13
+ """
14
+ Create the following Elliptic Curve over domain.
15
+
16
+ `y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}`
17
+
18
+ The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``,
19
+ is given then it creates a curve with the following form:
20
+
21
+ `y^{2} = x^{3} + a_{4} x + a_{6}`
22
+
23
+ Examples
24
+ ========
25
+
26
+ References
27
+ ==========
28
+
29
+ .. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition
30
+ .. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html
31
+ .. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition
32
+
33
+ """
34
+
35
+ def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus=0):
36
+ if modulus == 0:
37
+ domain = QQ
38
+ else:
39
+ domain = FF(modulus)
40
+ a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6))
41
+ self._domain = domain
42
+ self.modulus = modulus
43
+ # Calculate discriminant
44
+ b2 = a1**2 + 4 * a2
45
+ b4 = 2 * a4 + a1 * a3
46
+ b6 = a3**2 + 4 * a6
47
+ b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2
48
+ self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8
49
+ self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6
50
+ self._a1 = a1
51
+ self._a2 = a2
52
+ self._a3 = a3
53
+ self._a4 = a4
54
+ self._a6 = a6
55
+ x, y, z = symbols('x y z')
56
+ self.x, self.y, self.z = x, y, z
57
+ self._poly = Poly(y**2*z + a1*x*y*z + a3*y*z**2 - x**3 - a2*x**2*z - a4*x*z**2 - a6*z**3, domain=domain)
58
+ if isinstance(self._domain, FiniteField):
59
+ self._rank = 0
60
+ elif isinstance(self._domain, RationalField):
61
+ self._rank = None
62
+
63
+ def __call__(self, x, y, z=1):
64
+ return EllipticCurvePoint(x, y, z, self)
65
+
66
+ def __contains__(self, point):
67
+ if is_sequence(point):
68
+ if len(point) == 2:
69
+ z1 = 1
70
+ else:
71
+ z1 = point[2]
72
+ x1, y1 = point[:2]
73
+ elif isinstance(point, EllipticCurvePoint):
74
+ x1, y1, z1 = point.x, point.y, point.z
75
+ else:
76
+ raise ValueError('Invalid point.')
77
+ if self.characteristic == 0 and z1 == 0:
78
+ return True
79
+ return self._poly.subs({self.x: x1, self.y: y1, self.z: z1}) == 0
80
+
81
+ def __repr__(self):
82
+ return self._poly.__repr__()
83
+
84
+ def minimal(self):
85
+ """
86
+ Return minimal Weierstrass equation.
87
+
88
+ Examples
89
+ ========
90
+
91
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
92
+
93
+ >>> e1 = EllipticCurve(-10, -20, 0, -1, 1)
94
+ >>> e1.minimal()
95
+ Poly(-x**3 + 13392*x*z**2 + y**2*z + 1080432*z**3, x, y, z, domain='QQ')
96
+
97
+ """
98
+ char = self.characteristic
99
+ if char == 2:
100
+ return self
101
+ if char == 3:
102
+ return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus)
103
+ c4 = self._b2**2 - 24*self._b4
104
+ c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6
105
+ return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus)
106
+
107
+ def points(self):
108
+ """
109
+ Return points of curve over Finite Field.
110
+
111
+ Examples
112
+ ========
113
+
114
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
115
+ >>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5)
116
+ >>> e2.points()
117
+ {(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)}
118
+
119
+ """
120
+
121
+ char = self.characteristic
122
+ all_pt = set()
123
+ if char >= 1:
124
+ for i in range(char):
125
+ congruence_eq = self._poly.subs({self.x: i, self.z: 1}).expr
126
+ sol = polynomial_congruence(congruence_eq, char)
127
+ all_pt.update((i, num) for num in sol)
128
+ return all_pt
129
+ else:
130
+ raise ValueError("Infinitely many points")
131
+
132
+ def points_x(self, x):
133
+ """Returns points on the curve for the given x-coordinate."""
134
+ pt = []
135
+ if self._domain == QQ:
136
+ for y in solve(self._poly.subs(self.x, x)):
137
+ pt.append((x, y))
138
+ else:
139
+ congruence_eq = self._poly.subs({self.x: x, self.z: 1}).expr
140
+ for y in polynomial_congruence(congruence_eq, self.characteristic):
141
+ pt.append((x, y))
142
+ return pt
143
+
144
+ def torsion_points(self):
145
+ """
146
+ Return torsion points of curve over Rational number.
147
+
148
+ Return point objects those are finite order.
149
+ According to Nagell-Lutz theorem, torsion point p(x, y)
150
+ x and y are integers, either y = 0 or y**2 is divisor
151
+ of discriminent. According to Mazur's theorem, there are
152
+ at most 15 points in torsion collection.
153
+
154
+ Examples
155
+ ========
156
+
157
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
158
+ >>> e2 = EllipticCurve(-43, 166)
159
+ >>> sorted(e2.torsion_points())
160
+ [(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)]
161
+
162
+ """
163
+ if self.characteristic > 0:
164
+ raise ValueError("No torsion point for Finite Field.")
165
+ l = [EllipticCurvePoint.point_at_infinity(self)]
166
+ for xx in solve(self._poly.subs({self.y: 0, self.z: 1})):
167
+ if xx.is_rational:
168
+ l.append(self(xx, 0))
169
+ for i in divisors(self.discriminant, generator=True):
170
+ j = int(i**.5)
171
+ if j**2 == i:
172
+ for xx in solve(self._poly.subs({self.y: j, self.z: 1})):
173
+ if not xx.is_rational:
174
+ continue
175
+ p = self(xx, j)
176
+ if p.order() != oo:
177
+ l.extend([p, -p])
178
+ return l
179
+
180
+ @property
181
+ def characteristic(self):
182
+ """
183
+ Return domain characteristic.
184
+
185
+ Examples
186
+ ========
187
+
188
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
189
+ >>> e2 = EllipticCurve(-43, 166)
190
+ >>> e2.characteristic
191
+ 0
192
+
193
+ """
194
+ return self._domain.characteristic()
195
+
196
+ @property
197
+ def discriminant(self):
198
+ """
199
+ Return curve discriminant.
200
+
201
+ Examples
202
+ ========
203
+
204
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
205
+ >>> e2 = EllipticCurve(0, 17)
206
+ >>> e2.discriminant
207
+ -124848
208
+
209
+ """
210
+ return int(self._discrim)
211
+
212
+ @property
213
+ def is_singular(self):
214
+ """
215
+ Return True if curve discriminant is equal to zero.
216
+ """
217
+ return self.discriminant == 0
218
+
219
+ @property
220
+ def j_invariant(self):
221
+ """
222
+ Return curve j-invariant.
223
+
224
+ Examples
225
+ ========
226
+
227
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
228
+ >>> e1 = EllipticCurve(-2, 0, 0, 1, 1)
229
+ >>> e1.j_invariant
230
+ 1404928/389
231
+
232
+ """
233
+ c4 = self._b2**2 - 24*self._b4
234
+ return self._domain.to_sympy(c4**3 / self._discrim)
235
+
236
+ @property
237
+ def order(self):
238
+ """
239
+ Number of points in Finite field.
240
+
241
+ Examples
242
+ ========
243
+
244
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
245
+ >>> e2 = EllipticCurve(1, 0, modulus=19)
246
+ >>> e2.order
247
+ 19
248
+
249
+ """
250
+ if self.characteristic == 0:
251
+ raise NotImplementedError("Still not implemented")
252
+ return len(self.points())
253
+
254
+ @property
255
+ def rank(self):
256
+ """
257
+ Number of independent points of infinite order.
258
+
259
+ For Finite field, it must be 0.
260
+ """
261
+ if self._rank is not None:
262
+ return self._rank
263
+ raise NotImplementedError("Still not implemented")
264
+
265
+
266
+ class EllipticCurvePoint:
267
+ """
268
+ Point of Elliptic Curve
269
+
270
+ Examples
271
+ ========
272
+
273
+ >>> from sympy.ntheory.elliptic_curve import EllipticCurve
274
+ >>> e1 = EllipticCurve(-17, 16)
275
+ >>> p1 = e1(0, -4, 1)
276
+ >>> p2 = e1(1, 0)
277
+ >>> p1 + p2
278
+ (15, -56)
279
+ >>> e3 = EllipticCurve(-1, 9)
280
+ >>> e3(1, -3) * 3
281
+ (664/169, 17811/2197)
282
+ >>> (e3(1, -3) * 3).order()
283
+ oo
284
+ >>> e2 = EllipticCurve(-2, 0, 0, 1, 1)
285
+ >>> p = e2(-1,1)
286
+ >>> q = e2(0, -1)
287
+ >>> p+q
288
+ (4, 8)
289
+ >>> p-q
290
+ (1, 0)
291
+ >>> 3*p-5*q
292
+ (328/361, -2800/6859)
293
+ """
294
+
295
+ @staticmethod
296
+ def point_at_infinity(curve):
297
+ return EllipticCurvePoint(0, 1, 0, curve)
298
+
299
+ def __init__(self, x, y, z, curve):
300
+ dom = curve._domain.convert
301
+ self.x = dom(x)
302
+ self.y = dom(y)
303
+ self.z = dom(z)
304
+ self._curve = curve
305
+ self._domain = self._curve._domain
306
+ if not self._curve.__contains__(self):
307
+ raise ValueError("The curve does not contain this point")
308
+
309
+ def __add__(self, p):
310
+ if self.z == 0:
311
+ return p
312
+ if p.z == 0:
313
+ return self
314
+ x1, y1 = self.x/self.z, self.y/self.z
315
+ x2, y2 = p.x/p.z, p.y/p.z
316
+ a1 = self._curve._a1
317
+ a2 = self._curve._a2
318
+ a3 = self._curve._a3
319
+ a4 = self._curve._a4
320
+ a6 = self._curve._a6
321
+ if x1 != x2:
322
+ slope = (y1 - y2) / (x1 - x2)
323
+ yint = (y1 * x2 - y2 * x1) / (x2 - x1)
324
+ else:
325
+ if (y1 + y2) == 0:
326
+ return self.point_at_infinity(self._curve)
327
+ slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
328
+ yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
329
+ x3 = slope**2 + a1*slope - a2 - x1 - x2
330
+ y3 = -(slope + a1) * x3 - yint - a3
331
+ return self._curve(x3, y3, 1)
332
+
333
+ def __lt__(self, other):
334
+ return (self.x, self.y, self.z) < (other.x, other.y, other.z)
335
+
336
+ def __mul__(self, n):
337
+ n = as_int(n)
338
+ r = self.point_at_infinity(self._curve)
339
+ if n == 0:
340
+ return r
341
+ if n < 0:
342
+ return -self * -n
343
+ p = self
344
+ while n:
345
+ if n & 1:
346
+ r = r + p
347
+ n >>= 1
348
+ p = p + p
349
+ return r
350
+
351
+ def __rmul__(self, n):
352
+ return self * n
353
+
354
+ def __neg__(self):
355
+ return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)
356
+
357
+ def __repr__(self):
358
+ if self.z == 0:
359
+ return 'O'
360
+ dom = self._curve._domain
361
+ try:
362
+ return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y))
363
+ except TypeError:
364
+ pass
365
+ return '({}, {})'.format(self.x, self.y)
366
+
367
+ def __sub__(self, other):
368
+ return self.__add__(-other)
369
+
370
+ def order(self):
371
+ """
372
+ Return point order n where nP = 0.
373
+
374
+ """
375
+ if self.z == 0:
376
+ return 1
377
+ if self.y == 0: # P = -P
378
+ return 2
379
+ p = self * 2
380
+ if p.y == -self.y: # 2P = -P
381
+ return 3
382
+ i = 2
383
+ if self._domain != QQ:
384
+ while int(p.x) == p.x and int(p.y) == p.y:
385
+ p = self + p
386
+ i += 1
387
+ if p.z == 0:
388
+ return i
389
+ return oo
390
+ while p.x.numerator == p.x and p.y.numerator == p.y:
391
+ p = self + p
392
+ i += 1
393
+ if i > 12:
394
+ return oo
395
+ if p.z == 0:
396
+ return i
397
+ return oo
.venv/lib/python3.12/site-packages/sympy/ntheory/factor_.py ADDED
@@ -0,0 +1,2841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Integer factorization
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from bisect import bisect_left
7
+ from collections import defaultdict, OrderedDict
8
+ from collections.abc import MutableMapping
9
+ import math
10
+
11
+ from sympy.core.containers import Dict
12
+ from sympy.core.mul import Mul
13
+ from sympy.core.numbers import Rational, Integer
14
+ from sympy.core.intfunc import num_digits
15
+ from sympy.core.power import Pow
16
+ from sympy.core.random import _randint
17
+ from sympy.core.singleton import S
18
+ from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
19
+ sqrtrem, iroot, bit_scan1, remove)
20
+ from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
21
+ from .generate import sieve, primerange, nextprime
22
+ from .digits import digits
23
+ from sympy.utilities.decorator import deprecated
24
+ from sympy.utilities.iterables import flatten
25
+ from sympy.utilities.misc import as_int, filldedent
26
+ from .ecm import _ecm_one_factor
27
+
28
+
29
+ def smoothness(n):
30
+ """
31
+ Return the B-smooth and B-power smooth values of n.
32
+
33
+ The smoothness of n is the largest prime factor of n; the power-
34
+ smoothness is the largest divisor raised to its multiplicity.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.ntheory.factor_ import smoothness
40
+ >>> smoothness(2**7*3**2)
41
+ (3, 128)
42
+ >>> smoothness(2**4*13)
43
+ (13, 16)
44
+ >>> smoothness(2)
45
+ (2, 2)
46
+
47
+ See Also
48
+ ========
49
+
50
+ factorint, smoothness_p
51
+ """
52
+
53
+ if n == 1:
54
+ return (1, 1) # not prime, but otherwise this causes headaches
55
+ facs = factorint(n)
56
+ return max(facs), max(m**facs[m] for m in facs)
57
+
58
+
59
+ def smoothness_p(n, m=-1, power=0, visual=None):
60
+ """
61
+ Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
62
+ where:
63
+
64
+ 1. p**M is the base-p divisor of n
65
+ 2. sm(p + m) is the smoothness of p + m (m = -1 by default)
66
+ 3. psm(p + m) is the power smoothness of p + m
67
+
68
+ The list is sorted according to smoothness (default) or by power smoothness
69
+ if power=1.
70
+
71
+ The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
72
+ factor govern the results that are obtained from the p +/- 1 type factoring
73
+ methods.
74
+
75
+ >>> from sympy.ntheory.factor_ import smoothness_p, factorint
76
+ >>> smoothness_p(10431, m=1)
77
+ (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
78
+ >>> smoothness_p(10431)
79
+ (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
80
+ >>> smoothness_p(10431, power=1)
81
+ (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
82
+
83
+ If visual=True then an annotated string will be returned:
84
+
85
+ >>> print(smoothness_p(21477639576571, visual=1))
86
+ p**i=4410317**1 has p-1 B=1787, B-pow=1787
87
+ p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
88
+
89
+ This string can also be generated directly from a factorization dictionary
90
+ and vice versa:
91
+
92
+ >>> factorint(17*9)
93
+ {3: 2, 17: 1}
94
+ >>> smoothness_p(_)
95
+ 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
96
+ >>> smoothness_p(_)
97
+ {3: 2, 17: 1}
98
+
99
+ The table of the output logic is:
100
+
101
+ ====== ====== ======= =======
102
+ | Visual
103
+ ------ ----------------------
104
+ Input True False other
105
+ ====== ====== ======= =======
106
+ dict str tuple str
107
+ str str tuple dict
108
+ tuple str tuple str
109
+ n str tuple tuple
110
+ mul str tuple tuple
111
+ ====== ====== ======= =======
112
+
113
+ See Also
114
+ ========
115
+
116
+ factorint, smoothness
117
+ """
118
+
119
+ # visual must be True, False or other (stored as None)
120
+ if visual in (1, 0):
121
+ visual = bool(visual)
122
+ elif visual not in (True, False):
123
+ visual = None
124
+
125
+ if isinstance(n, str):
126
+ if visual:
127
+ return n
128
+ d = {}
129
+ for li in n.splitlines():
130
+ k, v = [int(i) for i in
131
+ li.split('has')[0].split('=')[1].split('**')]
132
+ d[k] = v
133
+ if visual is not True and visual is not False:
134
+ return d
135
+ return smoothness_p(d, visual=False)
136
+ elif not isinstance(n, tuple):
137
+ facs = factorint(n, visual=False)
138
+
139
+ if power:
140
+ k = -1
141
+ else:
142
+ k = 1
143
+ if isinstance(n, tuple):
144
+ rv = n
145
+ else:
146
+ rv = (m, sorted([(f,
147
+ tuple([M] + list(smoothness(f + m))))
148
+ for f, M in list(facs.items())],
149
+ key=lambda x: (x[1][k], x[0])))
150
+
151
+ if visual is False or (visual is not True) and (type(n) in [int, Mul]):
152
+ return rv
153
+ lines = []
154
+ for dat in rv[1]:
155
+ dat = flatten(dat)
156
+ dat.insert(2, m)
157
+ lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
158
+ return '\n'.join(lines)
159
+
160
+
161
+ def multiplicity(p, n):
162
+ """
163
+ Find the greatest integer m such that p**m divides n.
164
+
165
+ Examples
166
+ ========
167
+
168
+ >>> from sympy import multiplicity, Rational
169
+ >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
170
+ [0, 1, 2, 3, 3]
171
+ >>> multiplicity(3, Rational(1, 9))
172
+ -2
173
+
174
+ Note: when checking for the multiplicity of a number in a
175
+ large factorial it is most efficient to send it as an unevaluated
176
+ factorial or to call ``multiplicity_in_factorial`` directly:
177
+
178
+ >>> from sympy.ntheory import multiplicity_in_factorial
179
+ >>> from sympy import factorial
180
+ >>> p = factorial(25)
181
+ >>> n = 2**100
182
+ >>> nfac = factorial(n, evaluate=False)
183
+ >>> multiplicity(p, nfac)
184
+ 52818775009509558395695966887
185
+ >>> _ == multiplicity_in_factorial(p, n)
186
+ True
187
+
188
+ See Also
189
+ ========
190
+
191
+ trailing
192
+
193
+ """
194
+ try:
195
+ p, n = as_int(p), as_int(n)
196
+ except ValueError:
197
+ from sympy.functions.combinatorial.factorials import factorial
198
+ if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
199
+ p = Rational(p)
200
+ n = Rational(n)
201
+ if p.q == 1:
202
+ if n.p == 1:
203
+ return -multiplicity(p.p, n.q)
204
+ return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
205
+ elif p.p == 1:
206
+ return multiplicity(p.q, n.q)
207
+ else:
208
+ like = min(
209
+ multiplicity(p.p, n.p),
210
+ multiplicity(p.q, n.q))
211
+ cross = min(
212
+ multiplicity(p.q, n.p),
213
+ multiplicity(p.p, n.q))
214
+ return like - cross
215
+ elif (isinstance(p, (SYMPY_INTS, Integer)) and
216
+ isinstance(n, factorial) and
217
+ isinstance(n.args[0], Integer) and
218
+ n.args[0] >= 0):
219
+ return multiplicity_in_factorial(p, n.args[0])
220
+ raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
221
+
222
+ if n == 0:
223
+ raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
224
+ return remove(n, p)[1]
225
+
226
+
227
+ def multiplicity_in_factorial(p, n):
228
+ """return the largest integer ``m`` such that ``p**m`` divides ``n!``
229
+ without calculating the factorial of ``n``.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ p : Integer
235
+ positive integer
236
+ n : Integer
237
+ non-negative integer
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy.ntheory import multiplicity_in_factorial
243
+ >>> from sympy import factorial
244
+
245
+ >>> multiplicity_in_factorial(2, 3)
246
+ 1
247
+
248
+ An instructive use of this is to tell how many trailing zeros
249
+ a given factorial has. For example, there are 6 in 25!:
250
+
251
+ >>> factorial(25)
252
+ 15511210043330985984000000
253
+ >>> multiplicity_in_factorial(10, 25)
254
+ 6
255
+
256
+ For large factorials, it is much faster/feasible to use
257
+ this function rather than computing the actual factorial:
258
+
259
+ >>> multiplicity_in_factorial(factorial(25), 2**100)
260
+ 52818775009509558395695966887
261
+
262
+ See Also
263
+ ========
264
+
265
+ multiplicity
266
+
267
+ """
268
+
269
+ p, n = as_int(p), as_int(n)
270
+
271
+ if p <= 0:
272
+ raise ValueError('expecting positive integer got %s' % p )
273
+
274
+ if n < 0:
275
+ raise ValueError('expecting non-negative integer got %s' % n )
276
+
277
+ # keep only the largest of a given multiplicity since those
278
+ # of a given multiplicity will be goverened by the behavior
279
+ # of the largest factor
280
+ f = defaultdict(int)
281
+ for k, v in factorint(p).items():
282
+ f[v] = max(k, f[v])
283
+ # multiplicity of p in n! depends on multiplicity
284
+ # of prime `k` in p, so we floor divide by `v`
285
+ # and keep it if smaller than the multiplicity of p
286
+ # seen so far
287
+ return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
288
+
289
+
290
+ def _perfect_power(n, next_p=2):
291
+ """ Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
292
+ perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
293
+
294
+ Explanation
295
+ ===========
296
+
297
+ This is a low-level helper for ``perfect_power``, for internal use.
298
+
299
+ Parameters
300
+ ==========
301
+
302
+ n : int
303
+ assume that n is a nonnegative integer
304
+ next_p : int
305
+ Assume that n has no factor less than next_p.
306
+ i.e., all(n % p for p in range(2, next_p)) is True
307
+
308
+ Examples
309
+ ========
310
+ >>> from sympy.ntheory.factor_ import _perfect_power
311
+ >>> _perfect_power(16)
312
+ (2, 4)
313
+ >>> _perfect_power(17)
314
+ False
315
+
316
+ """
317
+ if n <= 3:
318
+ return False
319
+
320
+ factors = {}
321
+ g = 0
322
+ multi = 1
323
+
324
+ def done(n, factors, g, multi):
325
+ g = gcd(g, multi)
326
+ if g == 1:
327
+ return False
328
+ factors[n] = multi
329
+ return math.prod(p**(e//g) for p, e in factors.items()), g
330
+
331
+ # If n is small, only trial factoring is faster
332
+ if n <= 1_000_000:
333
+ n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
334
+ if n > 1:
335
+ return False
336
+ g = gcd(*factors.values())
337
+ if g == 1:
338
+ return False
339
+ return math.prod(p**(e//g) for p, e in factors.items()), g
340
+
341
+ # divide by 2
342
+ if next_p < 3:
343
+ g = bit_scan1(n)
344
+ if g:
345
+ if g == 1:
346
+ return False
347
+ n >>= g
348
+ factors[2] = g
349
+ if n == 1:
350
+ return 2, g
351
+ else:
352
+ # If `m**g`, then we have found perfect power.
353
+ # Otherwise, there is no possibility of perfect power, especially if `g` is prime.
354
+ m, _exact = iroot(n, g)
355
+ if _exact:
356
+ return 2*m, g
357
+ elif isprime(g):
358
+ return False
359
+ next_p = 3
360
+
361
+ # square number?
362
+ while n & 7 == 1: # n % 8 == 1:
363
+ m, _exact = iroot(n, 2)
364
+ if _exact:
365
+ n = m
366
+ multi <<= 1
367
+ else:
368
+ break
369
+ if n < next_p**3:
370
+ return done(n, factors, g, multi)
371
+
372
+ # trial factoring
373
+ # Since the maximum value an exponent can take is `log_{next_p}(n)`,
374
+ # the number of exponents to be checked can be reduced by performing a trial factoring.
375
+ # The value of `tf_max` needs more consideration.
376
+ tf_max = n.bit_length()//27 + 24
377
+ if next_p < tf_max:
378
+ for p in primerange(next_p, tf_max):
379
+ m, t = remove(n, p)
380
+ if t:
381
+ n = m
382
+ t *= multi
383
+ _g = gcd(g, t)
384
+ if _g == 1:
385
+ return False
386
+ factors[p] = t
387
+ if n == 1:
388
+ return math.prod(p**(e//_g)
389
+ for p, e in factors.items()), _g
390
+ elif g == 0 or _g < g: # If g is updated
391
+ g = _g
392
+ m, _exact = iroot(n**multi, g)
393
+ if _exact:
394
+ return m * math.prod(p**(e//g)
395
+ for p, e in factors.items()), g
396
+ elif isprime(g):
397
+ return False
398
+ next_p = tf_max
399
+ if n < next_p**3:
400
+ return done(n, factors, g, multi)
401
+
402
+ # check iroot
403
+ if g:
404
+ # If g is non-zero, the exponent is a divisor of g.
405
+ # 2 can be omitted since it has already been checked.
406
+ prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
407
+ else:
408
+ # The maximum possible value of the exponent is `log_{next_p}(n)`.
409
+ # To compensate for the presence of computational error, 2 is added.
410
+ prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
411
+ logn = math.log2(n)
412
+ threshold = logn / 40 # Threshold for direct calculation
413
+ for p in prime_iter:
414
+ if threshold < p:
415
+ # If p is large, find the power root p directly without `iroot`.
416
+ while True:
417
+ b = pow(2, logn / p)
418
+ rb = int(b + 0.5)
419
+ if abs(rb - b) < 0.01 and rb**p == n:
420
+ n = rb
421
+ multi *= p
422
+ logn = math.log2(n)
423
+ else:
424
+ break
425
+ else:
426
+ while True:
427
+ m, _exact = iroot(n, p)
428
+ if _exact:
429
+ n = m
430
+ multi *= p
431
+ logn = math.log2(n)
432
+ else:
433
+ break
434
+ if n < next_p**(p + 2):
435
+ break
436
+ return done(n, factors, g, multi)
437
+
438
+
439
+ def perfect_power(n, candidates=None, big=True, factor=True):
440
+ """
441
+ Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
442
+ perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
443
+ perfect power). A ValueError is raised if ``n`` is not Rational.
444
+
445
+ By default, the base is recursively decomposed and the exponents
446
+ collected so the largest possible ``e`` is sought. If ``big=False``
447
+ then the smallest possible ``e`` (thus prime) will be chosen.
448
+
449
+ If ``factor=True`` then simultaneous factorization of ``n`` is
450
+ attempted since finding a factor indicates the only possible root
451
+ for ``n``. This is True by default since only a few small factors will
452
+ be tested in the course of searching for the perfect power.
453
+
454
+ The use of ``candidates`` is primarily for internal use; if provided,
455
+ False will be returned if ``n`` cannot be written as a power with one
456
+ of the candidates as an exponent and factoring (beyond testing for
457
+ a factor of 2) will not be attempted.
458
+
459
+ Examples
460
+ ========
461
+
462
+ >>> from sympy import perfect_power, Rational
463
+ >>> perfect_power(16)
464
+ (2, 4)
465
+ >>> perfect_power(16, big=False)
466
+ (4, 2)
467
+
468
+ Negative numbers can only have odd perfect powers:
469
+
470
+ >>> perfect_power(-4)
471
+ False
472
+ >>> perfect_power(-8)
473
+ (-2, 3)
474
+
475
+ Rationals are also recognized:
476
+
477
+ >>> perfect_power(Rational(1, 2)**3)
478
+ (1/2, 3)
479
+ >>> perfect_power(Rational(-3, 2)**3)
480
+ (-3/2, 3)
481
+
482
+ Notes
483
+ =====
484
+
485
+ To know whether an integer is a perfect power of 2 use
486
+
487
+ >>> is2pow = lambda n: bool(n and not n & (n - 1))
488
+ >>> [(i, is2pow(i)) for i in range(5)]
489
+ [(0, False), (1, True), (2, True), (3, False), (4, True)]
490
+
491
+ It is not necessary to provide ``candidates``. When provided
492
+ it will be assumed that they are ints. The first one that is
493
+ larger than the computed maximum possible exponent will signal
494
+ failure for the routine.
495
+
496
+ >>> perfect_power(3**8, [9])
497
+ False
498
+ >>> perfect_power(3**8, [2, 4, 8])
499
+ (3, 8)
500
+ >>> perfect_power(3**8, [4, 8], big=False)
501
+ (9, 4)
502
+
503
+ See Also
504
+ ========
505
+ sympy.core.intfunc.integer_nthroot
506
+ sympy.ntheory.primetest.is_square
507
+ """
508
+ # negative handling
509
+ if n < 0:
510
+ if candidates is None:
511
+ pp = perfect_power(-n, big=True, factor=factor)
512
+ if not pp:
513
+ return False
514
+
515
+ b, e = pp
516
+ e2 = e & (-e)
517
+ b, e = b ** e2, e // e2
518
+
519
+ if e <= 1:
520
+ return False
521
+
522
+ if big or isprime(e):
523
+ return -b, e
524
+
525
+ for p in primerange(3, e + 1):
526
+ if e % p == 0:
527
+ return - b ** (e // p), p
528
+
529
+ odd_candidates = {i for i in candidates if i % 2}
530
+ if not odd_candidates:
531
+ return False
532
+
533
+ pp = perfect_power(-n, odd_candidates, big, factor)
534
+ if pp:
535
+ return -pp[0], pp[1]
536
+
537
+ return False
538
+
539
+ # non-integer handling
540
+ if isinstance(n, Rational) and not isinstance(n, Integer):
541
+ p, q = n.p, n.q
542
+
543
+ if p == 1:
544
+ qq = perfect_power(q, candidates, big, factor)
545
+ return (S.One / qq[0], qq[1]) if qq is not False else False
546
+
547
+ if not (pp:=perfect_power(p, factor=factor)):
548
+ return False
549
+ if not (qq:=perfect_power(q, factor=factor)):
550
+ return False
551
+ (num_base, num_exp), (den_base, den_exp) = pp, qq
552
+
553
+ def compute_tuple(exponent):
554
+ """Helper to compute final result given an exponent"""
555
+ new_num = num_base ** (num_exp // exponent)
556
+ new_den = den_base ** (den_exp // exponent)
557
+ return n.func(new_num, new_den), exponent
558
+
559
+ if candidates:
560
+ valid_candidates = [i for i in candidates
561
+ if num_exp % i == 0 and den_exp % i == 0]
562
+ if not valid_candidates:
563
+ return False
564
+
565
+ e = max(valid_candidates) if big else min(valid_candidates)
566
+ return compute_tuple(e)
567
+
568
+ g = math.gcd(num_exp, den_exp)
569
+ if g == 1:
570
+ return False
571
+
572
+ if big:
573
+ return compute_tuple(g)
574
+
575
+ e = next(p for p in primerange(2, g + 1) if g % p == 0)
576
+ return compute_tuple(e)
577
+
578
+ if candidates is not None:
579
+ candidates = set(candidates)
580
+
581
+ # positive integer handling
582
+ n = as_int(n)
583
+
584
+ if candidates is None and big:
585
+ return _perfect_power(n)
586
+
587
+ if n <= 3:
588
+ # no unique exponent for 0, 1
589
+ # 2 and 3 have exponents of 1
590
+ return False
591
+ logn = math.log2(n)
592
+ max_possible = int(logn) + 2 # only check values less than this
593
+ not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
594
+ min_possible = 2 + not_square
595
+ if not candidates:
596
+ candidates = primerange(min_possible, max_possible)
597
+ else:
598
+ candidates = sorted([i for i in candidates
599
+ if min_possible <= i < max_possible])
600
+ if n%2 == 0:
601
+ e = bit_scan1(n)
602
+ candidates = [i for i in candidates if e%i == 0]
603
+ if big:
604
+ candidates = reversed(candidates)
605
+ for e in candidates:
606
+ r, ok = iroot(n, e)
607
+ if ok:
608
+ return int(r), e
609
+ return False
610
+
611
+ def _factors():
612
+ rv = 2 + n % 2
613
+ while True:
614
+ yield rv
615
+ rv = nextprime(rv)
616
+
617
+ for fac, e in zip(_factors(), candidates):
618
+ # see if there is a factor present
619
+ if factor and n % fac == 0:
620
+ # find what the potential power is
621
+ e = remove(n, fac)[1]
622
+ # if it's a trivial power we are done
623
+ if e == 1:
624
+ return False
625
+
626
+ # maybe the e-th root of n is exact
627
+ r, exact = iroot(n, e)
628
+ if not exact:
629
+ # Having a factor, we know that e is the maximal
630
+ # possible value for a root of n.
631
+ # If n = fac**e*m can be written as a perfect
632
+ # power then see if m can be written as r**E where
633
+ # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
634
+ m = n//fac**e
635
+ rE = perfect_power(m, candidates=divisors(e, generator=True))
636
+ if not rE:
637
+ return False
638
+ else:
639
+ r, E = rE
640
+ r, e = fac**(e//E)*r, E
641
+ if not big:
642
+ e0 = primefactors(e)
643
+ if e0[0] != e:
644
+ r, e = r**(e//e0[0]), e0[0]
645
+ return int(r), e
646
+
647
+ # Weed out downright impossible candidates
648
+ if logn/e < 40:
649
+ b = 2.0**(logn/e)
650
+ if abs(int(b + 0.5) - b) > 0.01:
651
+ continue
652
+
653
+ # now see if the plausible e makes a perfect power
654
+ r, exact = iroot(n, e)
655
+ if exact:
656
+ if big:
657
+ m = perfect_power(r, big=big, factor=factor)
658
+ if m:
659
+ r, e = m[0], e*m[1]
660
+ return int(r), e
661
+
662
+ return False
663
+
664
+
665
+ class FactorCache(MutableMapping):
666
+ """ Provides a cache for prime factors.
667
+ ``factor_cache`` is pre-prepared as an instance of ``FactorCache``,
668
+ and ``factorint`` internally references it to speed up
669
+ the factorization of prime factors.
670
+
671
+ While cache is automatically added during the execution of ``factorint``,
672
+ users can also manually add prime factors independently.
673
+
674
+ >>> from sympy import factor_cache
675
+ >>> factor_cache[15] = 5
676
+
677
+ Furthermore, by customizing ``get_external``,
678
+ it is also possible to use external databases.
679
+ The following is an example using http://factordb.com .
680
+
681
+ .. code-block:: python
682
+
683
+ import requests
684
+ from sympy import factor_cache
685
+
686
+ def get_external(self, n: int) -> list[int] | None:
687
+ res = requests.get("http://factordb.com/api", params={"query": str(n)})
688
+ if res.status_code != requests.codes.ok:
689
+ return None
690
+ j = res.json()
691
+ if j.get("status") in ["FF", "P"]:
692
+ return list(int(p) for p, _ in j.get("factors"))
693
+
694
+ factor_cache.get_external = get_external
695
+
696
+ Be aware that writing this code will trigger internet access
697
+ to factordb.com when calling ``factorint``.
698
+
699
+ """
700
+ def __init__(self, maxsize: int | None = None):
701
+ self._cache: OrderedDict[int, int] = OrderedDict()
702
+ self.maxsize = maxsize
703
+
704
+ def __len__(self) -> int:
705
+ return len(self._cache)
706
+
707
+ def __contains__(self, n) -> bool:
708
+ return n in self._cache
709
+
710
+ def __getitem__(self, n: int) -> int:
711
+ factor = self.get(n)
712
+ if factor is None:
713
+ raise KeyError(f"{n} does not exist.")
714
+ return factor
715
+
716
+ def __setitem__(self, n: int, factor: int):
717
+ if not (1 < factor <= n and n % factor == 0 and isprime(factor)):
718
+ raise ValueError(f"{factor} is not a prime factor of {n}")
719
+ self._cache[n] = max(self._cache.get(n, 0), factor)
720
+ if self.maxsize is not None and len(self._cache) > self.maxsize:
721
+ self._cache.popitem(False)
722
+
723
+ def __delitem__(self, n: int):
724
+ if n not in self._cache:
725
+ raise KeyError(f"{n} does not exist.")
726
+ del self._cache[n]
727
+
728
+ def __iter__(self):
729
+ return self._cache.__iter__()
730
+
731
+ def cache_clear(self) -> None:
732
+ """ Clear the cache """
733
+ self._cache = OrderedDict()
734
+
735
+ @property
736
+ def maxsize(self) -> int | None:
737
+ """ Returns the maximum cache size; if ``None``, it is unlimited. """
738
+ return self._maxsize
739
+
740
+ @maxsize.setter
741
+ def maxsize(self, value: int | None) -> None:
742
+ if value is not None and value <= 0:
743
+ raise ValueError("maxsize must be None or a non-negative integer.")
744
+ self._maxsize = value
745
+ if value is not None:
746
+ while len(self._cache) > value:
747
+ self._cache.popitem(False)
748
+
749
+ def get(self, n: int, default=None):
750
+ """ Return the prime factor of ``n``.
751
+ If it does not exist in the cache, return the value of ``default``.
752
+ """
753
+ if n <= sieve._list[-1]:
754
+ if sieve._list[bisect_left(sieve._list, n)] == n:
755
+ return n
756
+ if n in self._cache:
757
+ self._cache.move_to_end(n)
758
+ return self._cache[n]
759
+ if factors := self.get_external(n):
760
+ self.add(n, factors)
761
+ return self._cache[n]
762
+ return default
763
+
764
+ def add(self, n: int, factors: list[int]) -> None:
765
+ for p in sorted(factors, reverse=True):
766
+ self[n] = p
767
+ n, _ = remove(n, p)
768
+
769
+ def get_external(self, n: int) -> list[int] | None:
770
+ return None
771
+
772
+
773
+ factor_cache = FactorCache(maxsize=1000)
774
+
775
+
776
+ def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
777
+ r"""
778
+ Use Pollard's rho method to try to extract a nontrivial factor
779
+ of ``n``. The returned factor may be a composite number. If no
780
+ factor is found, ``None`` is returned.
781
+
782
+ The algorithm generates pseudo-random values of x with a generator
783
+ function, replacing x with F(x). If F is not supplied then the
784
+ function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
785
+ Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
786
+ supplied; the ``a`` will be ignored if F was supplied.
787
+
788
+ The sequence of numbers generated by such functions generally have a
789
+ a lead-up to some number and then loop around back to that number and
790
+ begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
791
+ and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
792
+
793
+ For a given function, very different leader-loop values can be obtained
794
+ so it is a good idea to allow for retries:
795
+
796
+ >>> from sympy.ntheory.generate import cycle_length
797
+ >>> n = 16843009
798
+ >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
799
+ >>> for s in range(5):
800
+ ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
801
+ ...
802
+ loop length = 2489; leader length = 43
803
+ loop length = 78; leader length = 121
804
+ loop length = 1482; leader length = 100
805
+ loop length = 1482; leader length = 286
806
+ loop length = 1482; leader length = 101
807
+
808
+ Here is an explicit example where there is a three element leadup to
809
+ a sequence of 3 numbers (11, 14, 4) that then repeat:
810
+
811
+ >>> x=2
812
+ >>> for i in range(9):
813
+ ... print(x)
814
+ ... x=(x**2+12)%17
815
+ ...
816
+ 2
817
+ 16
818
+ 13
819
+ 11
820
+ 14
821
+ 4
822
+ 11
823
+ 14
824
+ 4
825
+ >>> next(cycle_length(lambda x: (x**2+12)%17, 2))
826
+ (3, 3)
827
+ >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
828
+ [2, 16, 13, 11, 14, 4]
829
+
830
+ Instead of checking the differences of all generated values for a gcd
831
+ with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
832
+ 2nd and 4th, 3rd and 6th until it has been detected that the loop has been
833
+ traversed. Loops may be many thousands of steps long before rho finds a
834
+ factor or reports failure. If ``max_steps`` is specified, the iteration
835
+ is cancelled with a failure after the specified number of steps.
836
+
837
+ Examples
838
+ ========
839
+
840
+ >>> from sympy import pollard_rho
841
+ >>> n=16843009
842
+ >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
843
+ >>> pollard_rho(n, F=F)
844
+ 257
845
+
846
+ Use the default setting with a bad value of ``a`` and no retries:
847
+
848
+ >>> pollard_rho(n, a=n-2, retries=0)
849
+
850
+ If retries is > 0 then perhaps the problem will correct itself when
851
+ new values are generated for a:
852
+
853
+ >>> pollard_rho(n, a=n-2, retries=1)
854
+ 257
855
+
856
+ References
857
+ ==========
858
+
859
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
860
+ A Computational Perspective", Springer, 2nd edition, 229-231
861
+
862
+ """
863
+ n = int(n)
864
+ if n < 5:
865
+ raise ValueError('pollard_rho should receive n > 4')
866
+ randint = _randint(seed + retries)
867
+ V = s
868
+ for i in range(retries + 1):
869
+ U = V
870
+ if not F:
871
+ F = lambda x: (pow(x, 2, n) + a) % n
872
+ j = 0
873
+ while 1:
874
+ if max_steps and (j > max_steps):
875
+ break
876
+ j += 1
877
+ U = F(U)
878
+ V = F(F(V)) # V is 2x further along than U
879
+ g = gcd(U - V, n)
880
+ if g == 1:
881
+ continue
882
+ if g == n:
883
+ break
884
+ return int(g)
885
+ V = randint(0, n - 1)
886
+ a = randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
887
+ F = None
888
+ return None
889
+
890
+
891
+ def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
892
+ """
893
+ Use Pollard's p-1 method to try to extract a nontrivial factor
894
+ of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
895
+
896
+ The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
897
+ The default is 2. If ``retries`` > 0 then if no factor is found after the
898
+ first attempt, a new ``a`` will be generated randomly (using the ``seed``)
899
+ and the process repeated.
900
+
901
+ Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
902
+
903
+ A search is made for factors next to even numbers having a power smoothness
904
+ less than ``B``. Choosing a larger B increases the likelihood of finding a
905
+ larger factor but takes longer. Whether a factor of n is found or not
906
+ depends on ``a`` and the power smoothness of the even number just less than
907
+ the factor p (hence the name p - 1).
908
+
909
+ Although some discussion of what constitutes a good ``a`` some
910
+ descriptions are hard to interpret. At the modular.math site referenced
911
+ below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
912
+ for every prime power divisor of N. But consider the following:
913
+
914
+ >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
915
+ >>> n=257*1009
916
+ >>> smoothness_p(n)
917
+ (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
918
+
919
+ So we should (and can) find a root with B=16:
920
+
921
+ >>> pollard_pm1(n, B=16, a=3)
922
+ 1009
923
+
924
+ If we attempt to increase B to 256 we find that it does not work:
925
+
926
+ >>> pollard_pm1(n, B=256)
927
+ >>>
928
+
929
+ But if the value of ``a`` is changed we find that only multiples of
930
+ 257 work, e.g.:
931
+
932
+ >>> pollard_pm1(n, B=256, a=257)
933
+ 1009
934
+
935
+ Checking different ``a`` values shows that all the ones that did not
936
+ work had a gcd value not equal to ``n`` but equal to one of the
937
+ factors:
938
+
939
+ >>> from sympy import ilcm, igcd, factorint, Pow
940
+ >>> M = 1
941
+ >>> for i in range(2, 256):
942
+ ... M = ilcm(M, i)
943
+ ...
944
+ >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
945
+ ... igcd(pow(a, M, n) - 1, n) != n])
946
+ {1009}
947
+
948
+ But does aM % d for every divisor of n give 1?
949
+
950
+ >>> aM = pow(255, M, n)
951
+ >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
952
+ [(257**1, 1), (1009**1, 1)]
953
+
954
+ No, only one of them. So perhaps the principle is that a root will
955
+ be found for a given value of B provided that:
956
+
957
+ 1) the power smoothness of the p - 1 value next to the root
958
+ does not exceed B
959
+ 2) a**M % p != 1 for any of the divisors of n.
960
+
961
+ By trying more than one ``a`` it is possible that one of them
962
+ will yield a factor.
963
+
964
+ Examples
965
+ ========
966
+
967
+ With the default smoothness bound, this number cannot be cracked:
968
+
969
+ >>> from sympy.ntheory import pollard_pm1
970
+ >>> pollard_pm1(21477639576571)
971
+
972
+ Increasing the smoothness bound helps:
973
+
974
+ >>> pollard_pm1(21477639576571, B=2000)
975
+ 4410317
976
+
977
+ Looking at the smoothness of the factors of this number we find:
978
+
979
+ >>> from sympy.ntheory.factor_ import smoothness_p, factorint
980
+ >>> print(smoothness_p(21477639576571, visual=1))
981
+ p**i=4410317**1 has p-1 B=1787, B-pow=1787
982
+ p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
983
+
984
+ The B and B-pow are the same for the p - 1 factorizations of the divisors
985
+ because those factorizations had a very large prime factor:
986
+
987
+ >>> factorint(4410317 - 1)
988
+ {2: 2, 617: 1, 1787: 1}
989
+ >>> factorint(4869863-1)
990
+ {2: 1, 2434931: 1}
991
+
992
+ Note that until B reaches the B-pow value of 1787, the number is not cracked;
993
+
994
+ >>> pollard_pm1(21477639576571, B=1786)
995
+ >>> pollard_pm1(21477639576571, B=1787)
996
+ 4410317
997
+
998
+ The B value has to do with the factors of the number next to the divisor,
999
+ not the divisors themselves. A worst case scenario is that the number next
1000
+ to the factor p has a large prime divisisor or is a perfect power. If these
1001
+ conditions apply then the power-smoothness will be about p/2 or p. The more
1002
+ realistic is that there will be a large prime factor next to p requiring
1003
+ a B value on the order of p/2. Although primes may have been searched for
1004
+ up to this level, the p/2 is a factor of p - 1, something that we do not
1005
+ know. The modular.math reference below states that 15% of numbers in the
1006
+ range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
1007
+ will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
1008
+ percentages are nearly reversed...but in that range the simple trial
1009
+ division is quite fast.
1010
+
1011
+ References
1012
+ ==========
1013
+
1014
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
1015
+ A Computational Perspective", Springer, 2nd edition, 236-238
1016
+ .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
1017
+ .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
1018
+ """
1019
+
1020
+ n = int(n)
1021
+ if n < 4 or B < 3:
1022
+ raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
1023
+ randint = _randint(seed + B)
1024
+
1025
+ # computing a**lcm(1,2,3,..B) % n for B > 2
1026
+ # it looks weird, but it's right: primes run [2, B]
1027
+ # and the answer's not right until the loop is done.
1028
+ for i in range(retries + 1):
1029
+ aM = a
1030
+ for p in sieve.primerange(2, B + 1):
1031
+ e = int(math.log(B, p))
1032
+ aM = pow(aM, pow(p, e), n)
1033
+ g = gcd(aM - 1, n)
1034
+ if 1 < g < n:
1035
+ return int(g)
1036
+
1037
+ # get a new a:
1038
+ # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
1039
+ # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
1040
+ # give a zero, too, so we set the range as [2, n-2]. Some references
1041
+ # say 'a' should be coprime to n, but either will detect factors.
1042
+ a = randint(2, n - 2)
1043
+
1044
+
1045
+ def _trial(factors, n, candidates, verbose=False):
1046
+ """
1047
+ Helper function for integer factorization. Trial factors ``n`
1048
+ against all integers given in the sequence ``candidates``
1049
+ and updates the dict ``factors`` in-place. Returns the reduced
1050
+ value of ``n`` and a flag indicating whether any factors were found.
1051
+ """
1052
+ if verbose:
1053
+ factors0 = list(factors.keys())
1054
+ nfactors = len(factors)
1055
+ for d in candidates:
1056
+ if n % d == 0:
1057
+ if n != d:
1058
+ factor_cache[n] = d
1059
+ n, m = remove(n // d, d)
1060
+ factors[d] = m + 1
1061
+ if verbose:
1062
+ for k in sorted(set(factors).difference(set(factors0))):
1063
+ print(factor_msg % (k, factors[k]))
1064
+ return int(n), len(factors) != nfactors
1065
+
1066
+
1067
+ def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
1068
+ verbose, next_p):
1069
+ """
1070
+ Helper function for integer factorization. Checks if ``n``
1071
+ is a prime or a perfect power, and in those cases updates the factorization.
1072
+ """
1073
+ if verbose:
1074
+ print('Check for termination')
1075
+ if n == 1:
1076
+ if verbose:
1077
+ print(complete_msg)
1078
+ return True
1079
+ if n < next_p**2 or isprime(n):
1080
+ factor_cache[n] = n
1081
+ factors[int(n)] = 1
1082
+ if verbose:
1083
+ print(complete_msg)
1084
+ return True
1085
+
1086
+ # since we've already been factoring there is no need to do
1087
+ # simultaneous factoring with the power check
1088
+ p = _perfect_power(n, next_p)
1089
+ if not p:
1090
+ return False
1091
+ base, exp = p
1092
+ if base < next_p**2 or isprime(base):
1093
+ factor_cache[n] = base
1094
+ factors[base] = exp
1095
+ else:
1096
+ facs = factorint(base, limit, use_trial, use_rho, use_pm1,
1097
+ verbose=False)
1098
+ for b, e in facs.items():
1099
+ if verbose:
1100
+ print(factor_msg % (b, e))
1101
+ factors[b] = exp*e
1102
+ if verbose:
1103
+ print(complete_msg)
1104
+ return True
1105
+
1106
+
1107
+ trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
1108
+ trial_msg = "Trial division with primes [%i ... %i]"
1109
+ rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
1110
+ pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
1111
+ ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
1112
+ factor_msg = '\t%i ** %i'
1113
+ fermat_msg = 'Close factors satisfying Fermat condition found.'
1114
+ complete_msg = 'Factorization is complete.'
1115
+
1116
+
1117
+ def _factorint_small(factors, n, limit, fail_max, next_p=2):
1118
+ """
1119
+ Return the value of n and either a 0 (indicating that factorization up
1120
+ to the limit was complete) or else the next near-prime that would have
1121
+ been tested.
1122
+
1123
+ Factoring stops if there are fail_max unsuccessful tests in a row.
1124
+
1125
+ If factors of n were found they will be in the factors dictionary as
1126
+ {factor: multiplicity} and the returned value of n will have had those
1127
+ factors removed. The factors dictionary is modified in-place.
1128
+
1129
+ """
1130
+
1131
+ def done(n, d):
1132
+ """return n, d if the sqrt(n) was not reached yet, else
1133
+ n, 0 indicating that factoring is done.
1134
+ """
1135
+ if d*d <= n:
1136
+ return n, d
1137
+ return n, 0
1138
+
1139
+ limit2 = limit**2
1140
+ threshold2 = min(n, limit2)
1141
+
1142
+ if next_p < 3:
1143
+ if not n & 1:
1144
+ m = bit_scan1(n)
1145
+ factors[2] = m
1146
+ n >>= m
1147
+ threshold2 = min(n, limit2)
1148
+ next_p = 3
1149
+ if threshold2 < 9: # next_p**2 = 9
1150
+ return done(n, next_p)
1151
+
1152
+ if next_p < 5:
1153
+ if not n % 3:
1154
+ n //= 3
1155
+ m = 1
1156
+ while not n % 3:
1157
+ n //= 3
1158
+ m += 1
1159
+ if m == 20:
1160
+ n, mm = remove(n, 3)
1161
+ m += mm
1162
+ break
1163
+ factors[3] = m
1164
+ threshold2 = min(n, limit2)
1165
+ next_p = 5
1166
+ if threshold2 < 25: # next_p**2 = 25
1167
+ return done(n, next_p)
1168
+
1169
+ # Because of the order of checks, starting from `min_p = 6k+5`,
1170
+ # useless checks are caused.
1171
+ # We want to calculate
1172
+ # next_p += [-1, -2, 3, 2, 1, 0][next_p % 6]
1173
+ p6 = next_p % 6
1174
+ next_p += (-1 if p6 < 2 else 5) - p6
1175
+
1176
+ fails = 0
1177
+ while fails < fail_max:
1178
+ # next_p % 6 == 5
1179
+ if n % next_p:
1180
+ fails += 1
1181
+ else:
1182
+ n //= next_p
1183
+ m = 1
1184
+ while not n % next_p:
1185
+ n //= next_p
1186
+ m += 1
1187
+ if m == 20:
1188
+ n, mm = remove(n, next_p)
1189
+ m += mm
1190
+ break
1191
+ factors[next_p] = m
1192
+ fails = 0
1193
+ threshold2 = min(n, limit2)
1194
+ next_p += 2
1195
+ if threshold2 < next_p**2:
1196
+ return done(n, next_p)
1197
+
1198
+ # next_p % 6 == 1
1199
+ if n % next_p:
1200
+ fails += 1
1201
+ else:
1202
+ n //= next_p
1203
+ m = 1
1204
+ while not n % next_p:
1205
+ n //= next_p
1206
+ m += 1
1207
+ if m == 20:
1208
+ n, mm = remove(n, next_p)
1209
+ m += mm
1210
+ break
1211
+ factors[next_p] = m
1212
+ fails = 0
1213
+ threshold2 = min(n, limit2)
1214
+ next_p += 4
1215
+ if threshold2 < next_p**2:
1216
+ return done(n, next_p)
1217
+ return done(n, next_p)
1218
+
1219
+
1220
+ def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
1221
+ use_ecm=True, verbose=False, visual=None, multiple=False):
1222
+ r"""
1223
+ Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
1224
+ the prime factors of ``n`` as keys and their respective multiplicities
1225
+ as values. For example:
1226
+
1227
+ >>> from sympy.ntheory import factorint
1228
+ >>> factorint(2000) # 2000 = (2**4) * (5**3)
1229
+ {2: 4, 5: 3}
1230
+ >>> factorint(65537) # This number is prime
1231
+ {65537: 1}
1232
+
1233
+ For input less than 2, factorint behaves as follows:
1234
+
1235
+ - ``factorint(1)`` returns the empty factorization, ``{}``
1236
+ - ``factorint(0)`` returns ``{0:1}``
1237
+ - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
1238
+
1239
+ Partial Factorization:
1240
+
1241
+ If ``limit`` (> 3) is specified, the search is stopped after performing
1242
+ trial division up to (and including) the limit (or taking a
1243
+ corresponding number of rho/p-1 steps). This is useful if one has
1244
+ a large number and only is interested in finding small factors (if
1245
+ any). Note that setting a limit does not prevent larger factors
1246
+ from being found early; it simply means that the largest factor may
1247
+ be composite. Since checking for perfect power is relatively cheap, it is
1248
+ done regardless of the limit setting.
1249
+
1250
+ This number, for example, has two small factors and a huge
1251
+ semi-prime factor that cannot be reduced easily:
1252
+
1253
+ >>> from sympy.ntheory import isprime
1254
+ >>> a = 1407633717262338957430697921446883
1255
+ >>> f = factorint(a, limit=10000)
1256
+ >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
1257
+ True
1258
+ >>> isprime(max(f))
1259
+ False
1260
+
1261
+ This number has a small factor and a residual perfect power whose
1262
+ base is greater than the limit:
1263
+
1264
+ >>> factorint(3*101**7, limit=5)
1265
+ {3: 1, 101: 7}
1266
+
1267
+ List of Factors:
1268
+
1269
+ If ``multiple`` is set to ``True`` then a list containing the
1270
+ prime factors including multiplicities is returned.
1271
+
1272
+ >>> factorint(24, multiple=True)
1273
+ [2, 2, 2, 3]
1274
+
1275
+ Visual Factorization:
1276
+
1277
+ If ``visual`` is set to ``True``, then it will return a visual
1278
+ factorization of the integer. For example:
1279
+
1280
+ >>> from sympy import pprint
1281
+ >>> pprint(factorint(4200, visual=True))
1282
+ 3 1 2 1
1283
+ 2 *3 *5 *7
1284
+
1285
+ Note that this is achieved by using the evaluate=False flag in Mul
1286
+ and Pow. If you do other manipulations with an expression where
1287
+ evaluate=False, it may evaluate. Therefore, you should use the
1288
+ visual option only for visualization, and use the normal dictionary
1289
+ returned by visual=False if you want to perform operations on the
1290
+ factors.
1291
+
1292
+ You can easily switch between the two forms by sending them back to
1293
+ factorint:
1294
+
1295
+ >>> from sympy import Mul
1296
+ >>> regular = factorint(1764); regular
1297
+ {2: 2, 3: 2, 7: 2}
1298
+ >>> pprint(factorint(regular))
1299
+ 2 2 2
1300
+ 2 *3 *7
1301
+
1302
+ >>> visual = factorint(1764, visual=True); pprint(visual)
1303
+ 2 2 2
1304
+ 2 *3 *7
1305
+ >>> print(factorint(visual))
1306
+ {2: 2, 3: 2, 7: 2}
1307
+
1308
+ If you want to send a number to be factored in a partially factored form
1309
+ you can do so with a dictionary or unevaluated expression:
1310
+
1311
+ >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
1312
+ {2: 10, 3: 3}
1313
+ >>> factorint(Mul(4, 12, evaluate=False))
1314
+ {2: 4, 3: 1}
1315
+
1316
+ The table of the output logic is:
1317
+
1318
+ ====== ====== ======= =======
1319
+ Visual
1320
+ ------ ----------------------
1321
+ Input True False other
1322
+ ====== ====== ======= =======
1323
+ dict mul dict mul
1324
+ n mul dict dict
1325
+ mul mul dict dict
1326
+ ====== ====== ======= =======
1327
+
1328
+ Notes
1329
+ =====
1330
+
1331
+ Algorithm:
1332
+
1333
+ The function switches between multiple algorithms. Trial division
1334
+ quickly finds small factors (of the order 1-5 digits), and finds
1335
+ all large factors if given enough time. The Pollard rho and p-1
1336
+ algorithms are used to find large factors ahead of time; they
1337
+ will often find factors of the order of 10 digits within a few
1338
+ seconds:
1339
+
1340
+ >>> factors = factorint(12345678910111213141516)
1341
+ >>> for base, exp in sorted(factors.items()):
1342
+ ... print('%s %s' % (base, exp))
1343
+ ...
1344
+ 2 2
1345
+ 2507191691 1
1346
+ 1231026625769 1
1347
+
1348
+ Any of these methods can optionally be disabled with the following
1349
+ boolean parameters:
1350
+
1351
+ - ``use_trial``: Toggle use of trial division
1352
+ - ``use_rho``: Toggle use of Pollard's rho method
1353
+ - ``use_pm1``: Toggle use of Pollard's p-1 method
1354
+
1355
+ ``factorint`` also periodically checks if the remaining part is
1356
+ a prime number or a perfect power, and in those cases stops.
1357
+
1358
+ For unevaluated factorial, it uses Legendre's formula(theorem).
1359
+
1360
+
1361
+ If ``verbose`` is set to ``True``, detailed progress is printed.
1362
+
1363
+ See Also
1364
+ ========
1365
+
1366
+ smoothness, smoothness_p, divisors
1367
+
1368
+ """
1369
+ if isinstance(n, Dict):
1370
+ n = dict(n)
1371
+ if multiple:
1372
+ fac = factorint(n, limit=limit, use_trial=use_trial,
1373
+ use_rho=use_rho, use_pm1=use_pm1,
1374
+ verbose=verbose, visual=False, multiple=False)
1375
+ factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
1376
+ for p in sorted(fac)), [])
1377
+ return factorlist
1378
+
1379
+ factordict = {}
1380
+ if visual and not isinstance(n, (Mul, dict)):
1381
+ factordict = factorint(n, limit=limit, use_trial=use_trial,
1382
+ use_rho=use_rho, use_pm1=use_pm1,
1383
+ verbose=verbose, visual=False)
1384
+ elif isinstance(n, Mul):
1385
+ factordict = {int(k): int(v) for k, v in
1386
+ n.as_powers_dict().items()}
1387
+ elif isinstance(n, dict):
1388
+ factordict = n
1389
+ if factordict and isinstance(n, (Mul, dict)):
1390
+ # check it
1391
+ for key in list(factordict.keys()):
1392
+ if isprime(key):
1393
+ continue
1394
+ e = factordict.pop(key)
1395
+ d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
1396
+ use_pm1=use_pm1, verbose=verbose, visual=False)
1397
+ for k, v in d.items():
1398
+ if k in factordict:
1399
+ factordict[k] += v*e
1400
+ else:
1401
+ factordict[k] = v*e
1402
+ if visual or (type(n) is dict and
1403
+ visual is not True and
1404
+ visual is not False):
1405
+ if factordict == {}:
1406
+ return S.One
1407
+ if -1 in factordict:
1408
+ factordict.pop(-1)
1409
+ args = [S.NegativeOne]
1410
+ else:
1411
+ args = []
1412
+ args.extend([Pow(*i, evaluate=False)
1413
+ for i in sorted(factordict.items())])
1414
+ return Mul(*args, evaluate=False)
1415
+ elif isinstance(n, (dict, Mul)):
1416
+ return factordict
1417
+
1418
+ assert use_trial or use_rho or use_pm1 or use_ecm
1419
+
1420
+ from sympy.functions.combinatorial.factorials import factorial
1421
+ if isinstance(n, factorial):
1422
+ x = as_int(n.args[0])
1423
+ if x >= 20:
1424
+ factors = {}
1425
+ m = 2 # to initialize the if condition below
1426
+ for p in sieve.primerange(2, x + 1):
1427
+ if m > 1:
1428
+ m, q = 0, x // p
1429
+ while q != 0:
1430
+ m += q
1431
+ q //= p
1432
+ factors[p] = m
1433
+ if factors and verbose:
1434
+ for k in sorted(factors):
1435
+ print(factor_msg % (k, factors[k]))
1436
+ if verbose:
1437
+ print(complete_msg)
1438
+ return factors
1439
+ else:
1440
+ # if n < 20!, direct computation is faster
1441
+ # since it uses a lookup table
1442
+ n = n.func(x)
1443
+
1444
+ n = as_int(n)
1445
+ if limit:
1446
+ limit = int(limit)
1447
+ use_ecm = False
1448
+
1449
+ # special cases
1450
+ if n < 0:
1451
+ factors = factorint(
1452
+ -n, limit=limit, use_trial=use_trial, use_rho=use_rho,
1453
+ use_pm1=use_pm1, verbose=verbose, visual=False)
1454
+ factors[-1] = 1
1455
+ return factors
1456
+
1457
+ if limit and limit < 2:
1458
+ if n == 1:
1459
+ return {}
1460
+ return {n: 1}
1461
+ elif n < 10:
1462
+ # doing this we are assured of getting a limit > 2
1463
+ # when we have to compute it later
1464
+ return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
1465
+ {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
1466
+
1467
+ factors = {}
1468
+
1469
+ # do simplistic factorization
1470
+ if verbose:
1471
+ sn = str(n)
1472
+ if len(sn) > 50:
1473
+ print('Factoring %s' % sn[:5] + \
1474
+ '..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
1475
+ else:
1476
+ print('Factoring', n)
1477
+
1478
+ # this is the preliminary factorization for small factors
1479
+ # We want to guarantee that there are no small prime factors,
1480
+ # so we run even if `use_trial` is False.
1481
+ small = 2**15
1482
+ fail_max = 600
1483
+ small = min(small, limit or small)
1484
+ if verbose:
1485
+ print(trial_int_msg % (2, small, fail_max))
1486
+ n, next_p = _factorint_small(factors, n, small, fail_max)
1487
+ if factors and verbose:
1488
+ for k in sorted(factors):
1489
+ print(factor_msg % (k, factors[k]))
1490
+ if next_p == 0:
1491
+ if n > 1:
1492
+ factors[int(n)] = 1
1493
+ if verbose:
1494
+ print(complete_msg)
1495
+ return factors
1496
+ # Check if it exists in the cache
1497
+ while p := factor_cache.get(n):
1498
+ n, e = remove(n, p)
1499
+ factors[int(p)] = int(e)
1500
+ # first check if the simplistic run didn't finish
1501
+ # because of the limit and check for a perfect
1502
+ # power before exiting
1503
+ if limit and next_p > limit:
1504
+ if verbose:
1505
+ print('Exceeded limit:', limit)
1506
+ if _check_termination(factors, n, limit, use_trial,
1507
+ use_rho, use_pm1, verbose, next_p):
1508
+ return factors
1509
+ if n > 1:
1510
+ factors[int(n)] = 1
1511
+ return factors
1512
+ if _check_termination(factors, n, limit, use_trial,
1513
+ use_rho, use_pm1, verbose, next_p):
1514
+ return factors
1515
+
1516
+ # continue with more advanced factorization methods
1517
+ # ...do a Fermat test since it's so easy and we need the
1518
+ # square root anyway. Finding 2 factors is easy if they are
1519
+ # "close enough." This is the big root equivalent of dividing by
1520
+ # 2, 3, 5.
1521
+ sqrt_n = isqrt(n)
1522
+ a = sqrt_n + 1
1523
+ # If `n % 4 == 1`, `a` must be odd for `a**2 - n` to be a square number.
1524
+ if (n % 4 == 1) ^ (a & 1):
1525
+ a += 1
1526
+ a2 = a**2
1527
+ b2 = a2 - n
1528
+ for _ in range(3):
1529
+ b, fermat = sqrtrem(b2)
1530
+ if not fermat:
1531
+ if verbose:
1532
+ print(fermat_msg)
1533
+ for r in [a - b, a + b]:
1534
+ facs = factorint(r, limit=limit, use_trial=use_trial,
1535
+ use_rho=use_rho, use_pm1=use_pm1,
1536
+ verbose=verbose)
1537
+ for k, v in facs.items():
1538
+ factors[k] = factors.get(k, 0) + v
1539
+ factor_cache.add(n, facs)
1540
+ if verbose:
1541
+ print(complete_msg)
1542
+ return factors
1543
+ b2 += (a + 1) << 2 # equiv to (a + 2)**2 - n
1544
+ a += 2
1545
+
1546
+ # these are the limits for trial division which will
1547
+ # be attempted in parallel with pollard methods
1548
+ low, high = next_p, 2*next_p
1549
+
1550
+ # add 1 to make sure limit is reached in primerange calls
1551
+ _limit = (limit or sqrt_n) + 1
1552
+ iteration = 0
1553
+ while 1:
1554
+ high_ = min(high, _limit)
1555
+
1556
+ # Trial division
1557
+ if use_trial:
1558
+ if verbose:
1559
+ print(trial_msg % (low, high_))
1560
+ ps = sieve.primerange(low, high_)
1561
+ n, found_trial = _trial(factors, n, ps, verbose)
1562
+ next_p = high_
1563
+ if found_trial and _check_termination(factors, n, limit, use_trial,
1564
+ use_rho, use_pm1, verbose, next_p):
1565
+ return factors
1566
+ else:
1567
+ found_trial = False
1568
+
1569
+ if high > _limit:
1570
+ if verbose:
1571
+ print('Exceeded limit:', _limit)
1572
+ if n > 1:
1573
+ factors[int(n)] = 1
1574
+ if verbose:
1575
+ print(complete_msg)
1576
+ return factors
1577
+
1578
+ # Only used advanced methods when no small factors were found
1579
+ if not found_trial:
1580
+ # Pollard p-1
1581
+ if use_pm1:
1582
+ if verbose:
1583
+ print(pm1_msg % (low, high_))
1584
+ c = pollard_pm1(n, B=low, seed=high_)
1585
+ if c:
1586
+ if c < next_p**2 or isprime(c):
1587
+ ps = [c]
1588
+ else:
1589
+ ps = factorint(c, limit=limit,
1590
+ use_trial=use_trial,
1591
+ use_rho=use_rho,
1592
+ use_pm1=use_pm1,
1593
+ use_ecm=use_ecm,
1594
+ verbose=verbose)
1595
+ n, _ = _trial(factors, n, ps, verbose=False)
1596
+ if _check_termination(factors, n, limit, use_trial,
1597
+ use_rho, use_pm1, verbose, next_p):
1598
+ return factors
1599
+
1600
+ # Pollard rho
1601
+ if use_rho:
1602
+ if verbose:
1603
+ print(rho_msg % (1, low, high_))
1604
+ c = pollard_rho(n, retries=1, max_steps=low, seed=high_)
1605
+ if c:
1606
+ if c < next_p**2 or isprime(c):
1607
+ ps = [c]
1608
+ else:
1609
+ ps = factorint(c, limit=limit,
1610
+ use_trial=use_trial,
1611
+ use_rho=use_rho,
1612
+ use_pm1=use_pm1,
1613
+ use_ecm=use_ecm,
1614
+ verbose=verbose)
1615
+ n, _ = _trial(factors, n, ps, verbose=False)
1616
+ if _check_termination(factors, n, limit, use_trial,
1617
+ use_rho, use_pm1, verbose, next_p):
1618
+ return factors
1619
+ # Use subexponential algorithms if use_ecm
1620
+ # Use pollard algorithms for finding small factors for 3 iterations
1621
+ # if after small factors the number of digits of n >= 25 then use ecm
1622
+ iteration += 1
1623
+ if use_ecm and iteration >= 3 and num_digits(n) >= 24:
1624
+ break
1625
+ low, high = high, high*2
1626
+
1627
+ B1 = 10000
1628
+ B2 = 100*B1
1629
+ num_curves = 50
1630
+ while(1):
1631
+ if verbose:
1632
+ print(ecm_msg % (B1, B2, num_curves))
1633
+ factor = _ecm_one_factor(n, B1, B2, num_curves, seed=B1)
1634
+ if factor:
1635
+ if factor < next_p**2 or isprime(factor):
1636
+ ps = [factor]
1637
+ else:
1638
+ ps = factorint(factor, limit=limit,
1639
+ use_trial=use_trial,
1640
+ use_rho=use_rho,
1641
+ use_pm1=use_pm1,
1642
+ use_ecm=use_ecm,
1643
+ verbose=verbose)
1644
+ n, _ = _trial(factors, n, ps, verbose=False)
1645
+ if _check_termination(factors, n, limit, use_trial,
1646
+ use_rho, use_pm1, verbose, next_p):
1647
+ return factors
1648
+ B1 *= 5
1649
+ B2 = 100*B1
1650
+ num_curves *= 4
1651
+
1652
+
1653
+ def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
1654
+ verbose=False, visual=None, multiple=False):
1655
+ r"""
1656
+ Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
1657
+ the prime factors of ``r`` as keys and their respective multiplicities
1658
+ as values. For example:
1659
+
1660
+ >>> from sympy import factorrat, S
1661
+ >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
1662
+ {2: 3, 3: -2}
1663
+ >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
1664
+ {-1: 1, 3: -1, 7: -1, 47: -1}
1665
+
1666
+ Please see the docstring for ``factorint`` for detailed explanations
1667
+ and examples of the following keywords:
1668
+
1669
+ - ``limit``: Integer limit up to which trial division is done
1670
+ - ``use_trial``: Toggle use of trial division
1671
+ - ``use_rho``: Toggle use of Pollard's rho method
1672
+ - ``use_pm1``: Toggle use of Pollard's p-1 method
1673
+ - ``verbose``: Toggle detailed printing of progress
1674
+ - ``multiple``: Toggle returning a list of factors or dict
1675
+ - ``visual``: Toggle product form of output
1676
+ """
1677
+ if multiple:
1678
+ fac = factorrat(rat, limit=limit, use_trial=use_trial,
1679
+ use_rho=use_rho, use_pm1=use_pm1,
1680
+ verbose=verbose, visual=False, multiple=False)
1681
+ factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
1682
+ for p, _ in sorted(fac.items(),
1683
+ key=lambda elem: elem[0]
1684
+ if elem[1] > 0
1685
+ else 1/elem[0])), [])
1686
+ return factorlist
1687
+
1688
+ f = factorint(rat.p, limit=limit, use_trial=use_trial,
1689
+ use_rho=use_rho, use_pm1=use_pm1,
1690
+ verbose=verbose).copy()
1691
+ f = defaultdict(int, f)
1692
+ for p, e in factorint(rat.q, limit=limit,
1693
+ use_trial=use_trial,
1694
+ use_rho=use_rho,
1695
+ use_pm1=use_pm1,
1696
+ verbose=verbose).items():
1697
+ f[p] += -e
1698
+
1699
+ if len(f) > 1 and 1 in f:
1700
+ del f[1]
1701
+ if not visual:
1702
+ return dict(f)
1703
+ else:
1704
+ if -1 in f:
1705
+ f.pop(-1)
1706
+ args = [S.NegativeOne]
1707
+ else:
1708
+ args = []
1709
+ args.extend([Pow(*i, evaluate=False)
1710
+ for i in sorted(f.items())])
1711
+ return Mul(*args, evaluate=False)
1712
+
1713
+
1714
+ def primefactors(n, limit=None, verbose=False, **kwargs):
1715
+ """Return a sorted list of n's prime factors, ignoring multiplicity
1716
+ and any composite factor that remains if the limit was set too low
1717
+ for complete factorization. Unlike factorint(), primefactors() does
1718
+ not return -1 or 0.
1719
+
1720
+ Parameters
1721
+ ==========
1722
+
1723
+ n : integer
1724
+ limit, verbose, **kwargs :
1725
+ Additional keyword arguments to be passed to ``factorint``.
1726
+ Since ``kwargs`` is new in version 1.13,
1727
+ ``limit`` and ``verbose`` are retained for compatibility purposes.
1728
+
1729
+ Returns
1730
+ =======
1731
+
1732
+ list(int) : List of prime numbers dividing ``n``
1733
+
1734
+ Examples
1735
+ ========
1736
+
1737
+ >>> from sympy.ntheory import primefactors, factorint, isprime
1738
+ >>> primefactors(6)
1739
+ [2, 3]
1740
+ >>> primefactors(-5)
1741
+ [5]
1742
+
1743
+ >>> sorted(factorint(123456).items())
1744
+ [(2, 6), (3, 1), (643, 1)]
1745
+ >>> primefactors(123456)
1746
+ [2, 3, 643]
1747
+
1748
+ >>> sorted(factorint(10000000001, limit=200).items())
1749
+ [(101, 1), (99009901, 1)]
1750
+ >>> isprime(99009901)
1751
+ False
1752
+ >>> primefactors(10000000001, limit=300)
1753
+ [101]
1754
+
1755
+ See Also
1756
+ ========
1757
+
1758
+ factorint, divisors
1759
+
1760
+ """
1761
+ n = int(n)
1762
+ kwargs.update({"visual": None, "multiple": False,
1763
+ "limit": limit, "verbose": verbose})
1764
+ factors = sorted(factorint(n=n, **kwargs).keys())
1765
+ # We want to calculate
1766
+ # s = [f for f in factors if isprime(f)]
1767
+ s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
1768
+ if factors and isprime(factors[-1]):
1769
+ s += [factors[-1]]
1770
+ return s
1771
+
1772
+
1773
+ def _divisors(n, proper=False):
1774
+ """Helper function for divisors which generates the divisors.
1775
+
1776
+ Parameters
1777
+ ==========
1778
+
1779
+ n : int
1780
+ a nonnegative integer
1781
+ proper: bool
1782
+ If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).
1783
+
1784
+ """
1785
+ if n <= 1:
1786
+ if not proper and n:
1787
+ yield 1
1788
+ return
1789
+
1790
+ factordict = factorint(n)
1791
+ ps = sorted(factordict.keys())
1792
+
1793
+ def rec_gen(n=0):
1794
+ if n == len(ps):
1795
+ yield 1
1796
+ else:
1797
+ pows = [1]
1798
+ for _ in range(factordict[ps[n]]):
1799
+ pows.append(pows[-1] * ps[n])
1800
+ yield from (p * q for q in rec_gen(n + 1) for p in pows)
1801
+
1802
+ if proper:
1803
+ yield from (p for p in rec_gen() if p != n)
1804
+ else:
1805
+ yield from rec_gen()
1806
+
1807
+
1808
+ def divisors(n, generator=False, proper=False):
1809
+ r"""
1810
+ Return all divisors of n sorted from 1..n by default.
1811
+ If generator is ``True`` an unordered generator is returned.
1812
+
1813
+ The number of divisors of n can be quite large if there are many
1814
+ prime factors (counting repeated factors). If only the number of
1815
+ factors is desired use divisor_count(n).
1816
+
1817
+ Examples
1818
+ ========
1819
+
1820
+ >>> from sympy import divisors, divisor_count
1821
+ >>> divisors(24)
1822
+ [1, 2, 3, 4, 6, 8, 12, 24]
1823
+ >>> divisor_count(24)
1824
+ 8
1825
+
1826
+ >>> list(divisors(120, generator=True))
1827
+ [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
1828
+
1829
+ Notes
1830
+ =====
1831
+
1832
+ This is a slightly modified version of Tim Peters referenced at:
1833
+ https://stackoverflow.com/questions/1010381/python-factorization
1834
+
1835
+ See Also
1836
+ ========
1837
+
1838
+ primefactors, factorint, divisor_count
1839
+ """
1840
+ rv = _divisors(as_int(abs(n)), proper)
1841
+ return rv if generator else sorted(rv)
1842
+
1843
+
1844
+ def divisor_count(n, modulus=1, proper=False):
1845
+ """
1846
+ Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
1847
+ those that are divisible by ``modulus`` are counted. If ``proper`` is True
1848
+ then the divisor of ``n`` will not be counted.
1849
+
1850
+ Examples
1851
+ ========
1852
+
1853
+ >>> from sympy import divisor_count
1854
+ >>> divisor_count(6)
1855
+ 4
1856
+ >>> divisor_count(6, 2)
1857
+ 2
1858
+ >>> divisor_count(6, proper=True)
1859
+ 3
1860
+
1861
+ See Also
1862
+ ========
1863
+
1864
+ factorint, divisors, totient, proper_divisor_count
1865
+
1866
+ """
1867
+
1868
+ if not modulus:
1869
+ return 0
1870
+ elif modulus != 1:
1871
+ n, r = divmod(n, modulus)
1872
+ if r:
1873
+ return 0
1874
+ if n == 0:
1875
+ return 0
1876
+ n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
1877
+ if n and proper:
1878
+ n -= 1
1879
+ return n
1880
+
1881
+
1882
+ def proper_divisors(n, generator=False):
1883
+ """
1884
+ Return all divisors of n except n, sorted by default.
1885
+ If generator is ``True`` an unordered generator is returned.
1886
+
1887
+ Examples
1888
+ ========
1889
+
1890
+ >>> from sympy import proper_divisors, proper_divisor_count
1891
+ >>> proper_divisors(24)
1892
+ [1, 2, 3, 4, 6, 8, 12]
1893
+ >>> proper_divisor_count(24)
1894
+ 7
1895
+ >>> list(proper_divisors(120, generator=True))
1896
+ [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
1897
+
1898
+ See Also
1899
+ ========
1900
+
1901
+ factorint, divisors, proper_divisor_count
1902
+
1903
+ """
1904
+ return divisors(n, generator=generator, proper=True)
1905
+
1906
+
1907
+ def proper_divisor_count(n, modulus=1):
1908
+ """
1909
+ Return the number of proper divisors of ``n``.
1910
+
1911
+ Examples
1912
+ ========
1913
+
1914
+ >>> from sympy import proper_divisor_count
1915
+ >>> proper_divisor_count(6)
1916
+ 3
1917
+ >>> proper_divisor_count(6, modulus=2)
1918
+ 1
1919
+
1920
+ See Also
1921
+ ========
1922
+
1923
+ divisors, proper_divisors, divisor_count
1924
+
1925
+ """
1926
+ return divisor_count(n, modulus=modulus, proper=True)
1927
+
1928
+
1929
+ def _udivisors(n):
1930
+ """Helper function for udivisors which generates the unitary divisors.
1931
+
1932
+ Parameters
1933
+ ==========
1934
+
1935
+ n : int
1936
+ a nonnegative integer
1937
+
1938
+ """
1939
+ if n <= 1:
1940
+ if n == 1:
1941
+ yield 1
1942
+ return
1943
+
1944
+ factorpows = [p**e for p, e in factorint(n).items()]
1945
+ # We want to calculate
1946
+ # yield from (math.prod(s) for s in powersets(factorpows))
1947
+ for i in range(2**len(factorpows)):
1948
+ d = 1
1949
+ for k in range(i.bit_length()):
1950
+ if i & 1:
1951
+ d *= factorpows[k]
1952
+ i >>= 1
1953
+ yield d
1954
+
1955
+
1956
+ def udivisors(n, generator=False):
1957
+ r"""
1958
+ Return all unitary divisors of n sorted from 1..n by default.
1959
+ If generator is ``True`` an unordered generator is returned.
1960
+
1961
+ The number of unitary divisors of n can be quite large if there are many
1962
+ prime factors. If only the number of unitary divisors is desired use
1963
+ udivisor_count(n).
1964
+
1965
+ Examples
1966
+ ========
1967
+
1968
+ >>> from sympy.ntheory.factor_ import udivisors, udivisor_count
1969
+ >>> udivisors(15)
1970
+ [1, 3, 5, 15]
1971
+ >>> udivisor_count(15)
1972
+ 4
1973
+
1974
+ >>> sorted(udivisors(120, generator=True))
1975
+ [1, 3, 5, 8, 15, 24, 40, 120]
1976
+
1977
+ See Also
1978
+ ========
1979
+
1980
+ primefactors, factorint, divisors, divisor_count, udivisor_count
1981
+
1982
+ References
1983
+ ==========
1984
+
1985
+ .. [1] https://en.wikipedia.org/wiki/Unitary_divisor
1986
+ .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
1987
+
1988
+ """
1989
+ rv = _udivisors(as_int(abs(n)))
1990
+ return rv if generator else sorted(rv)
1991
+
1992
+
1993
+ def udivisor_count(n):
1994
+ """
1995
+ Return the number of unitary divisors of ``n``.
1996
+
1997
+ Parameters
1998
+ ==========
1999
+
2000
+ n : integer
2001
+
2002
+ Examples
2003
+ ========
2004
+
2005
+ >>> from sympy.ntheory.factor_ import udivisor_count
2006
+ >>> udivisor_count(120)
2007
+ 8
2008
+
2009
+ See Also
2010
+ ========
2011
+
2012
+ factorint, divisors, udivisors, divisor_count, totient
2013
+
2014
+ References
2015
+ ==========
2016
+
2017
+ .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
2018
+
2019
+ """
2020
+
2021
+ if n == 0:
2022
+ return 0
2023
+ return 2**len([p for p in factorint(n) if p > 1])
2024
+
2025
+
2026
+ def _antidivisors(n):
2027
+ """Helper function for antidivisors which generates the antidivisors.
2028
+
2029
+ Parameters
2030
+ ==========
2031
+
2032
+ n : int
2033
+ a nonnegative integer
2034
+
2035
+ """
2036
+ if n <= 2:
2037
+ return
2038
+ for d in _divisors(n):
2039
+ y = 2*d
2040
+ if n > y and n % y:
2041
+ yield y
2042
+ for d in _divisors(2*n-1):
2043
+ if n > d >= 2 and n % d:
2044
+ yield d
2045
+ for d in _divisors(2*n+1):
2046
+ if n > d >= 2 and n % d:
2047
+ yield d
2048
+
2049
+
2050
+ def antidivisors(n, generator=False):
2051
+ r"""
2052
+ Return all antidivisors of n sorted from 1..n by default.
2053
+
2054
+ Antidivisors [1]_ of n are numbers that do not divide n by the largest
2055
+ possible margin. If generator is True an unordered generator is returned.
2056
+
2057
+ Examples
2058
+ ========
2059
+
2060
+ >>> from sympy.ntheory.factor_ import antidivisors
2061
+ >>> antidivisors(24)
2062
+ [7, 16]
2063
+
2064
+ >>> sorted(antidivisors(128, generator=True))
2065
+ [3, 5, 15, 17, 51, 85]
2066
+
2067
+ See Also
2068
+ ========
2069
+
2070
+ primefactors, factorint, divisors, divisor_count, antidivisor_count
2071
+
2072
+ References
2073
+ ==========
2074
+
2075
+ .. [1] definition is described in https://oeis.org/A066272/a066272a.html
2076
+
2077
+ """
2078
+ rv = _antidivisors(as_int(abs(n)))
2079
+ return rv if generator else sorted(rv)
2080
+
2081
+
2082
+ def antidivisor_count(n):
2083
+ """
2084
+ Return the number of antidivisors [1]_ of ``n``.
2085
+
2086
+ Parameters
2087
+ ==========
2088
+
2089
+ n : integer
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy.ntheory.factor_ import antidivisor_count
2095
+ >>> antidivisor_count(13)
2096
+ 4
2097
+ >>> antidivisor_count(27)
2098
+ 5
2099
+
2100
+ See Also
2101
+ ========
2102
+
2103
+ factorint, divisors, antidivisors, divisor_count, totient
2104
+
2105
+ References
2106
+ ==========
2107
+
2108
+ .. [1] formula from https://oeis.org/A066272
2109
+
2110
+ """
2111
+
2112
+ n = as_int(abs(n))
2113
+ if n <= 2:
2114
+ return 0
2115
+ return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
2116
+ divisor_count(n) - divisor_count(n, 2) - 5
2117
+
2118
+ @deprecated("""\
2119
+ The `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.""",
2120
+ deprecated_since_version="1.13",
2121
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2122
+ def totient(n):
2123
+ r"""
2124
+ Calculate the Euler totient function phi(n)
2125
+
2126
+ .. deprecated:: 1.13
2127
+
2128
+ The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
2129
+ instead. See its documentation for more information. See
2130
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2131
+
2132
+ ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
2133
+ that are relatively prime to n.
2134
+
2135
+ Parameters
2136
+ ==========
2137
+
2138
+ n : integer
2139
+
2140
+ Examples
2141
+ ========
2142
+
2143
+ >>> from sympy.functions.combinatorial.numbers import totient
2144
+ >>> totient(1)
2145
+ 1
2146
+ >>> totient(25)
2147
+ 20
2148
+ >>> totient(45) == totient(5)*totient(9)
2149
+ True
2150
+
2151
+ See Also
2152
+ ========
2153
+
2154
+ divisor_count
2155
+
2156
+ References
2157
+ ==========
2158
+
2159
+ .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
2160
+ .. [2] https://mathworld.wolfram.com/TotientFunction.html
2161
+
2162
+ """
2163
+ from sympy.functions.combinatorial.numbers import totient as _totient
2164
+ return _totient(n)
2165
+
2166
+
2167
+ @deprecated("""\
2168
+ The `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.""",
2169
+ deprecated_since_version="1.13",
2170
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2171
+ def reduced_totient(n):
2172
+ r"""
2173
+ Calculate the Carmichael reduced totient function lambda(n)
2174
+
2175
+ .. deprecated:: 1.13
2176
+
2177
+ The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
2178
+ instead. See its documentation for more information. See
2179
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2180
+
2181
+ ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
2182
+ `k^m \equiv 1 \mod n` for all k relatively prime to n.
2183
+
2184
+ Examples
2185
+ ========
2186
+
2187
+ >>> from sympy.functions.combinatorial.numbers import reduced_totient
2188
+ >>> reduced_totient(1)
2189
+ 1
2190
+ >>> reduced_totient(8)
2191
+ 2
2192
+ >>> reduced_totient(30)
2193
+ 4
2194
+
2195
+ See Also
2196
+ ========
2197
+
2198
+ totient
2199
+
2200
+ References
2201
+ ==========
2202
+
2203
+ .. [1] https://en.wikipedia.org/wiki/Carmichael_function
2204
+ .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
2205
+
2206
+ """
2207
+ from sympy.functions.combinatorial.numbers import reduced_totient as _reduced_totient
2208
+ return _reduced_totient(n)
2209
+
2210
+
2211
+ @deprecated("""\
2212
+ The `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.""",
2213
+ deprecated_since_version="1.13",
2214
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2215
+ def divisor_sigma(n, k=1):
2216
+ r"""
2217
+ Calculate the divisor function `\sigma_k(n)` for positive integer n
2218
+
2219
+ .. deprecated:: 1.13
2220
+
2221
+ The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
2222
+ instead. See its documentation for more information. See
2223
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2224
+
2225
+ ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
2226
+
2227
+ If n's prime factorization is:
2228
+
2229
+ .. math ::
2230
+ n = \prod_{i=1}^\omega p_i^{m_i},
2231
+
2232
+ then
2233
+
2234
+ .. math ::
2235
+ \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
2236
+ + p_i^{m_ik}).
2237
+
2238
+ Parameters
2239
+ ==========
2240
+
2241
+ n : integer
2242
+
2243
+ k : integer, optional
2244
+ power of divisors in the sum
2245
+
2246
+ for k = 0, 1:
2247
+ ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
2248
+ ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
2249
+
2250
+ Default for k is 1.
2251
+
2252
+ Examples
2253
+ ========
2254
+
2255
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2256
+ >>> divisor_sigma(18, 0)
2257
+ 6
2258
+ >>> divisor_sigma(39, 1)
2259
+ 56
2260
+ >>> divisor_sigma(12, 2)
2261
+ 210
2262
+ >>> divisor_sigma(37)
2263
+ 38
2264
+
2265
+ See Also
2266
+ ========
2267
+
2268
+ divisor_count, totient, divisors, factorint
2269
+
2270
+ References
2271
+ ==========
2272
+
2273
+ .. [1] https://en.wikipedia.org/wiki/Divisor_function
2274
+
2275
+ """
2276
+ from sympy.functions.combinatorial.numbers import divisor_sigma as func_divisor_sigma
2277
+ return func_divisor_sigma(n, k)
2278
+
2279
+
2280
+ def _divisor_sigma(n:int, k:int=1) -> int:
2281
+ r""" Calculate the divisor function `\sigma_k(n)` for positive integer n
2282
+
2283
+ Parameters
2284
+ ==========
2285
+
2286
+ n : int
2287
+ positive integer
2288
+ k : int
2289
+ nonnegative integer
2290
+
2291
+ See Also
2292
+ ========
2293
+
2294
+ sympy.functions.combinatorial.numbers.divisor_sigma
2295
+
2296
+ """
2297
+ if k == 0:
2298
+ return math.prod(e + 1 for e in factorint(n).values())
2299
+ return math.prod((p**(k*(e + 1)) - 1)//(p**k - 1) for p, e in factorint(n).items())
2300
+
2301
+
2302
+ def core(n, t=2):
2303
+ r"""
2304
+ Calculate core(n, t) = `core_t(n)` of a positive integer n
2305
+
2306
+ ``core_2(n)`` is equal to the squarefree part of n
2307
+
2308
+ If n's prime factorization is:
2309
+
2310
+ .. math ::
2311
+ n = \prod_{i=1}^\omega p_i^{m_i},
2312
+
2313
+ then
2314
+
2315
+ .. math ::
2316
+ core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
2317
+
2318
+ Parameters
2319
+ ==========
2320
+
2321
+ n : integer
2322
+
2323
+ t : integer
2324
+ core(n, t) calculates the t-th power free part of n
2325
+
2326
+ ``core(n, 2)`` is the squarefree part of ``n``
2327
+ ``core(n, 3)`` is the cubefree part of ``n``
2328
+
2329
+ Default for t is 2.
2330
+
2331
+ Examples
2332
+ ========
2333
+
2334
+ >>> from sympy.ntheory.factor_ import core
2335
+ >>> core(24, 2)
2336
+ 6
2337
+ >>> core(9424, 3)
2338
+ 1178
2339
+ >>> core(379238)
2340
+ 379238
2341
+ >>> core(15**11, 10)
2342
+ 15
2343
+
2344
+ See Also
2345
+ ========
2346
+
2347
+ factorint, sympy.solvers.diophantine.diophantine.square_factor
2348
+
2349
+ References
2350
+ ==========
2351
+
2352
+ .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
2353
+
2354
+ """
2355
+
2356
+ n = as_int(n)
2357
+ t = as_int(t)
2358
+ if n <= 0:
2359
+ raise ValueError("n must be a positive integer")
2360
+ elif t <= 1:
2361
+ raise ValueError("t must be >= 2")
2362
+ else:
2363
+ y = 1
2364
+ for p, e in factorint(n).items():
2365
+ y *= p**(e % t)
2366
+ return y
2367
+
2368
+
2369
+ @deprecated("""\
2370
+ The `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.""",
2371
+ deprecated_since_version="1.13",
2372
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2373
+ def udivisor_sigma(n, k=1):
2374
+ r"""
2375
+ Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
2376
+
2377
+ .. deprecated:: 1.13
2378
+
2379
+ The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
2380
+ instead. See its documentation for more information. See
2381
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2382
+
2383
+ ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
2384
+
2385
+ If n's prime factorization is:
2386
+
2387
+ .. math ::
2388
+ n = \prod_{i=1}^\omega p_i^{m_i},
2389
+
2390
+ then
2391
+
2392
+ .. math ::
2393
+ \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
2394
+
2395
+ Parameters
2396
+ ==========
2397
+
2398
+ k : power of divisors in the sum
2399
+
2400
+ for k = 0, 1:
2401
+ ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
2402
+ ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
2403
+
2404
+ Default for k is 1.
2405
+
2406
+ Examples
2407
+ ========
2408
+
2409
+ >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
2410
+ >>> udivisor_sigma(18, 0)
2411
+ 4
2412
+ >>> udivisor_sigma(74, 1)
2413
+ 114
2414
+ >>> udivisor_sigma(36, 3)
2415
+ 47450
2416
+ >>> udivisor_sigma(111)
2417
+ 152
2418
+
2419
+ See Also
2420
+ ========
2421
+
2422
+ divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
2423
+ factorint
2424
+
2425
+ References
2426
+ ==========
2427
+
2428
+ .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
2429
+
2430
+ """
2431
+ from sympy.functions.combinatorial.numbers import udivisor_sigma as _udivisor_sigma
2432
+ return _udivisor_sigma(n, k)
2433
+
2434
+
2435
+ @deprecated("""\
2436
+ The `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.""",
2437
+ deprecated_since_version="1.13",
2438
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2439
+ def primenu(n):
2440
+ r"""
2441
+ Calculate the number of distinct prime factors for a positive integer n.
2442
+
2443
+ .. deprecated:: 1.13
2444
+
2445
+ The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
2446
+ instead. See its documentation for more information. See
2447
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2448
+
2449
+ If n's prime factorization is:
2450
+
2451
+ .. math ::
2452
+ n = \prod_{i=1}^k p_i^{m_i},
2453
+
2454
+ then ``primenu(n)`` or `\nu(n)` is:
2455
+
2456
+ .. math ::
2457
+ \nu(n) = k.
2458
+
2459
+ Examples
2460
+ ========
2461
+
2462
+ >>> from sympy.functions.combinatorial.numbers import primenu
2463
+ >>> primenu(1)
2464
+ 0
2465
+ >>> primenu(30)
2466
+ 3
2467
+
2468
+ See Also
2469
+ ========
2470
+
2471
+ factorint
2472
+
2473
+ References
2474
+ ==========
2475
+
2476
+ .. [1] https://mathworld.wolfram.com/PrimeFactor.html
2477
+
2478
+ """
2479
+ from sympy.functions.combinatorial.numbers import primenu as _primenu
2480
+ return _primenu(n)
2481
+
2482
+
2483
+ @deprecated("""\
2484
+ The `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.""",
2485
+ deprecated_since_version="1.13",
2486
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2487
+ def primeomega(n):
2488
+ r"""
2489
+ Calculate the number of prime factors counting multiplicities for a
2490
+ positive integer n.
2491
+
2492
+ .. deprecated:: 1.13
2493
+
2494
+ The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
2495
+ instead. See its documentation for more information. See
2496
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2497
+
2498
+ If n's prime factorization is:
2499
+
2500
+ .. math ::
2501
+ n = \prod_{i=1}^k p_i^{m_i},
2502
+
2503
+ then ``primeomega(n)`` or `\Omega(n)` is:
2504
+
2505
+ .. math ::
2506
+ \Omega(n) = \sum_{i=1}^k m_i.
2507
+
2508
+ Examples
2509
+ ========
2510
+
2511
+ >>> from sympy.functions.combinatorial.numbers import primeomega
2512
+ >>> primeomega(1)
2513
+ 0
2514
+ >>> primeomega(20)
2515
+ 3
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ factorint
2521
+
2522
+ References
2523
+ ==========
2524
+
2525
+ .. [1] https://mathworld.wolfram.com/PrimeFactor.html
2526
+
2527
+ """
2528
+ from sympy.functions.combinatorial.numbers import primeomega as _primeomega
2529
+ return _primeomega(n)
2530
+
2531
+
2532
+ def mersenne_prime_exponent(nth):
2533
+ """Returns the exponent ``i`` for the nth Mersenne prime (which
2534
+ has the form `2^i - 1`).
2535
+
2536
+ Examples
2537
+ ========
2538
+
2539
+ >>> from sympy.ntheory.factor_ import mersenne_prime_exponent
2540
+ >>> mersenne_prime_exponent(1)
2541
+ 2
2542
+ >>> mersenne_prime_exponent(20)
2543
+ 4423
2544
+ """
2545
+ n = as_int(nth)
2546
+ if n < 1:
2547
+ raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
2548
+ if n > 51:
2549
+ raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
2550
+ return MERSENNE_PRIME_EXPONENTS[n - 1]
2551
+
2552
+
2553
+ def is_perfect(n):
2554
+ """Returns True if ``n`` is a perfect number, else False.
2555
+
2556
+ A perfect number is equal to the sum of its positive, proper divisors.
2557
+
2558
+ Examples
2559
+ ========
2560
+
2561
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2562
+ >>> from sympy.ntheory.factor_ import is_perfect, divisors
2563
+ >>> is_perfect(20)
2564
+ False
2565
+ >>> is_perfect(6)
2566
+ True
2567
+ >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
2568
+ True
2569
+
2570
+ References
2571
+ ==========
2572
+
2573
+ .. [1] https://mathworld.wolfram.com/PerfectNumber.html
2574
+ .. [2] https://en.wikipedia.org/wiki/Perfect_number
2575
+
2576
+ """
2577
+ n = as_int(n)
2578
+ if n < 1:
2579
+ return False
2580
+ if n % 2 == 0:
2581
+ m = (n.bit_length() + 1) >> 1
2582
+ if (1 << (m - 1)) * ((1 << m) - 1) != n:
2583
+ # Even perfect numbers must be of the form `2^{m-1}(2^m-1)`
2584
+ return False
2585
+ return m in MERSENNE_PRIME_EXPONENTS or is_mersenne_prime(2**m - 1)
2586
+
2587
+ # n is an odd integer
2588
+ if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/
2589
+ return False
2590
+ if n % 105 == 0: # not divis by 105
2591
+ return False
2592
+ if all(n % m != r for m, r in [(12, 1), (468, 117), (324, 81)]):
2593
+ return False
2594
+ # there are many criteria that the factor structure of n
2595
+ # must meet; since we will have to factor it to test the
2596
+ # structure we will have the factors and can then check
2597
+ # to see whether it is a perfect number or not. So we
2598
+ # skip the structure checks and go straight to the final
2599
+ # test below.
2600
+ result = abundance(n) == 0
2601
+ if result:
2602
+ raise ValueError(filldedent('''In 1888, Sylvester stated: "
2603
+ ...a prolonged meditation on the subject has satisfied
2604
+ me that the existence of any one such [odd perfect number]
2605
+ -- its escape, so to say, from the complex web of conditions
2606
+ which hem it in on all sides -- would be little short of a
2607
+ miracle." I guess SymPy just found that miracle and it
2608
+ factors like this: %s''' % factorint(n)))
2609
+ return result
2610
+
2611
+
2612
+ def abundance(n):
2613
+ """Returns the difference between the sum of the positive
2614
+ proper divisors of a number and the number.
2615
+
2616
+ Examples
2617
+ ========
2618
+
2619
+ >>> from sympy.ntheory import abundance, is_perfect, is_abundant
2620
+ >>> abundance(6)
2621
+ 0
2622
+ >>> is_perfect(6)
2623
+ True
2624
+ >>> abundance(10)
2625
+ -2
2626
+ >>> is_abundant(10)
2627
+ False
2628
+ """
2629
+ return _divisor_sigma(n) - 2 * n
2630
+
2631
+
2632
+ def is_abundant(n):
2633
+ """Returns True if ``n`` is an abundant number, else False.
2634
+
2635
+ A abundant number is smaller than the sum of its positive proper divisors.
2636
+
2637
+ Examples
2638
+ ========
2639
+
2640
+ >>> from sympy.ntheory.factor_ import is_abundant
2641
+ >>> is_abundant(20)
2642
+ True
2643
+ >>> is_abundant(15)
2644
+ False
2645
+
2646
+ References
2647
+ ==========
2648
+
2649
+ .. [1] https://mathworld.wolfram.com/AbundantNumber.html
2650
+
2651
+ """
2652
+ n = as_int(n)
2653
+ if is_perfect(n):
2654
+ return False
2655
+ return n % 6 == 0 or bool(abundance(n) > 0)
2656
+
2657
+
2658
+ def is_deficient(n):
2659
+ """Returns True if ``n`` is a deficient number, else False.
2660
+
2661
+ A deficient number is greater than the sum of its positive proper divisors.
2662
+
2663
+ Examples
2664
+ ========
2665
+
2666
+ >>> from sympy.ntheory.factor_ import is_deficient
2667
+ >>> is_deficient(20)
2668
+ False
2669
+ >>> is_deficient(15)
2670
+ True
2671
+
2672
+ References
2673
+ ==========
2674
+
2675
+ .. [1] https://mathworld.wolfram.com/DeficientNumber.html
2676
+
2677
+ """
2678
+ n = as_int(n)
2679
+ if is_perfect(n):
2680
+ return False
2681
+ return bool(abundance(n) < 0)
2682
+
2683
+
2684
+ def is_amicable(m, n):
2685
+ """Returns True if the numbers `m` and `n` are "amicable", else False.
2686
+
2687
+ Amicable numbers are two different numbers so related that the sum
2688
+ of the proper divisors of each is equal to that of the other.
2689
+
2690
+ Examples
2691
+ ========
2692
+
2693
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2694
+ >>> from sympy.ntheory.factor_ import is_amicable
2695
+ >>> is_amicable(220, 284)
2696
+ True
2697
+ >>> divisor_sigma(220) == divisor_sigma(284)
2698
+ True
2699
+
2700
+ References
2701
+ ==========
2702
+
2703
+ .. [1] https://en.wikipedia.org/wiki/Amicable_numbers
2704
+
2705
+ """
2706
+ return m != n and m + n == _divisor_sigma(m) == _divisor_sigma(n)
2707
+
2708
+
2709
+ def is_carmichael(n):
2710
+ """ Returns True if the numbers `n` is Carmichael number, else False.
2711
+
2712
+ Parameters
2713
+ ==========
2714
+
2715
+ n : Integer
2716
+
2717
+ References
2718
+ ==========
2719
+
2720
+ .. [1] https://en.wikipedia.org/wiki/Carmichael_number
2721
+ .. [2] https://oeis.org/A002997
2722
+
2723
+ """
2724
+ if n < 561:
2725
+ return False
2726
+ return n % 2 and not isprime(n) and \
2727
+ all(e == 1 and (n - 1) % (p - 1) == 0 for p, e in factorint(n).items())
2728
+
2729
+
2730
+ def find_carmichael_numbers_in_range(x, y):
2731
+ """ Returns a list of the number of Carmichael in the range
2732
+
2733
+ See Also
2734
+ ========
2735
+
2736
+ is_carmichael
2737
+
2738
+ """
2739
+ if 0 <= x <= y:
2740
+ if x % 2 == 0:
2741
+ return [i for i in range(x + 1, y, 2) if is_carmichael(i)]
2742
+ else:
2743
+ return [i for i in range(x, y, 2) if is_carmichael(i)]
2744
+ else:
2745
+ raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
2746
+
2747
+
2748
+ def find_first_n_carmichaels(n):
2749
+ """ Returns the first n Carmichael numbers.
2750
+
2751
+ Parameters
2752
+ ==========
2753
+
2754
+ n : Integer
2755
+
2756
+ See Also
2757
+ ========
2758
+
2759
+ is_carmichael
2760
+
2761
+ """
2762
+ i = 561
2763
+ carmichaels = []
2764
+
2765
+ while len(carmichaels) < n:
2766
+ if is_carmichael(i):
2767
+ carmichaels.append(i)
2768
+ i += 2
2769
+
2770
+ return carmichaels
2771
+
2772
+
2773
+ def dra(n, b):
2774
+ """
2775
+ Returns the additive digital root of a natural number ``n`` in base ``b``
2776
+ which is a single digit value obtained by an iterative process of summing
2777
+ digits, on each iteration using the result from the previous iteration to
2778
+ compute a digit sum.
2779
+
2780
+ Examples
2781
+ ========
2782
+
2783
+ >>> from sympy.ntheory.factor_ import dra
2784
+ >>> dra(3110, 12)
2785
+ 8
2786
+
2787
+ References
2788
+ ==========
2789
+
2790
+ .. [1] https://en.wikipedia.org/wiki/Digital_root
2791
+
2792
+ """
2793
+
2794
+ num = abs(as_int(n))
2795
+ b = as_int(b)
2796
+ if b <= 1:
2797
+ raise ValueError("Base should be an integer greater than 1")
2798
+
2799
+ if num == 0:
2800
+ return 0
2801
+
2802
+ return (1 + (num - 1) % (b - 1))
2803
+
2804
+
2805
+ def drm(n, b):
2806
+ """
2807
+ Returns the multiplicative digital root of a natural number ``n`` in a given
2808
+ base ``b`` which is a single digit value obtained by an iterative process of
2809
+ multiplying digits, on each iteration using the result from the previous
2810
+ iteration to compute the digit multiplication.
2811
+
2812
+ Examples
2813
+ ========
2814
+
2815
+ >>> from sympy.ntheory.factor_ import drm
2816
+ >>> drm(9876, 10)
2817
+ 0
2818
+
2819
+ >>> drm(49, 10)
2820
+ 8
2821
+
2822
+ References
2823
+ ==========
2824
+
2825
+ .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
2826
+
2827
+ """
2828
+
2829
+ n = abs(as_int(n))
2830
+ b = as_int(b)
2831
+ if b <= 1:
2832
+ raise ValueError("Base should be an integer greater than 1")
2833
+ while n > b:
2834
+ mul = 1
2835
+ while n > 1:
2836
+ n, r = divmod(n, b)
2837
+ if r == 0:
2838
+ return 0
2839
+ mul *= r
2840
+ n = mul
2841
+ return n
.venv/lib/python3.12/site-packages/sympy/ntheory/generate.py ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generating and counting primes.
3
+
4
+ """
5
+
6
+ from bisect import bisect, bisect_left
7
+ from itertools import count
8
+ # Using arrays for sieving instead of lists greatly reduces
9
+ # memory consumption
10
+ from array import array as _array
11
+
12
+ from sympy.core.random import randint
13
+ from sympy.external.gmpy import sqrt
14
+ from .primetest import isprime
15
+ from sympy.utilities.decorator import deprecated
16
+ from sympy.utilities.misc import as_int
17
+
18
+
19
+ def _as_int_ceiling(a):
20
+ """ Wrapping ceiling in as_int will raise an error if there was a problem
21
+ determining whether the expression was exactly an integer or not."""
22
+ from sympy.functions.elementary.integers import ceiling
23
+ return as_int(ceiling(a))
24
+
25
+
26
+ class Sieve:
27
+ """A list of prime numbers, implemented as a dynamically
28
+ growing sieve of Eratosthenes. When a lookup is requested involving
29
+ an odd number that has not been sieved, the sieve is automatically
30
+ extended up to that number. Implementation details limit the number of
31
+ primes to ``2^32-1``.
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy import sieve
37
+ >>> sieve._reset() # this line for doctest only
38
+ >>> 25 in sieve
39
+ False
40
+ >>> sieve._list
41
+ array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
42
+ """
43
+
44
+ # data shared (and updated) by all Sieve instances
45
+ def __init__(self, sieve_interval=1_000_000):
46
+ """ Initial parameters for the Sieve class.
47
+
48
+ Parameters
49
+ ==========
50
+
51
+ sieve_interval (int): Amount of memory to be used
52
+
53
+ Raises
54
+ ======
55
+
56
+ ValueError
57
+ If ``sieve_interval`` is not positive.
58
+
59
+ """
60
+ self._n = 6
61
+ self._list = _array('L', [2, 3, 5, 7, 11, 13]) # primes
62
+ self._tlist = _array('L', [0, 1, 1, 2, 2, 4]) # totient
63
+ self._mlist = _array('i', [0, 1, -1, -1, 0, -1]) # mobius
64
+ if sieve_interval <= 0:
65
+ raise ValueError("sieve_interval should be a positive integer")
66
+ self.sieve_interval = sieve_interval
67
+ assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
68
+
69
+ def __repr__(self):
70
+ return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
71
+ "%s sieve (%i): %i, %i, %i, ... %i, %i\n"
72
+ "%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
73
+ 'prime', len(self._list),
74
+ self._list[0], self._list[1], self._list[2],
75
+ self._list[-2], self._list[-1],
76
+ 'totient', len(self._tlist),
77
+ self._tlist[0], self._tlist[1],
78
+ self._tlist[2], self._tlist[-2], self._tlist[-1],
79
+ 'mobius', len(self._mlist),
80
+ self._mlist[0], self._mlist[1],
81
+ self._mlist[2], self._mlist[-2], self._mlist[-1])
82
+
83
+ def _reset(self, prime=None, totient=None, mobius=None):
84
+ """Reset all caches (default). To reset one or more set the
85
+ desired keyword to True."""
86
+ if all(i is None for i in (prime, totient, mobius)):
87
+ prime = totient = mobius = True
88
+ if prime:
89
+ self._list = self._list[:self._n]
90
+ if totient:
91
+ self._tlist = self._tlist[:self._n]
92
+ if mobius:
93
+ self._mlist = self._mlist[:self._n]
94
+
95
+ def extend(self, n):
96
+ """Grow the sieve to cover all primes <= n.
97
+
98
+ Examples
99
+ ========
100
+
101
+ >>> from sympy import sieve
102
+ >>> sieve._reset() # this line for doctest only
103
+ >>> sieve.extend(30)
104
+ >>> sieve[10] == 29
105
+ True
106
+ """
107
+ n = int(n)
108
+ # `num` is even at any point in the function.
109
+ # This satisfies the condition required by `self._primerange`.
110
+ num = self._list[-1] + 1
111
+ if n < num:
112
+ return
113
+ num2 = num**2
114
+ while num2 <= n:
115
+ self._list += _array('L', self._primerange(num, num2))
116
+ num, num2 = num2, num2**2
117
+ # Merge the sieves
118
+ self._list += _array('L', self._primerange(num, n + 1))
119
+
120
+ def _primerange(self, a, b):
121
+ """ Generate all prime numbers in the range (a, b).
122
+
123
+ Parameters
124
+ ==========
125
+
126
+ a, b : positive integers assuming the following conditions
127
+ * a is an even number
128
+ * 2 < self._list[-1] < a < b < nextprime(self._list[-1])**2
129
+
130
+ Yields
131
+ ======
132
+
133
+ p (int): prime numbers such that ``a < p < b``
134
+
135
+ Examples
136
+ ========
137
+
138
+ >>> from sympy.ntheory.generate import Sieve
139
+ >>> s = Sieve()
140
+ >>> s._list[-1]
141
+ 13
142
+ >>> list(s._primerange(18, 31))
143
+ [19, 23, 29]
144
+
145
+ """
146
+ if b % 2:
147
+ b -= 1
148
+ while a < b:
149
+ block_size = min(self.sieve_interval, (b - a) // 2)
150
+ # Create the list such that block[x] iff (a + 2x + 1) is prime.
151
+ # Note that even numbers are not considered here.
152
+ block = [True] * block_size
153
+ for p in self._list[1:bisect(self._list, sqrt(a + 2 * block_size + 1))]:
154
+ for t in range((-(a + 1 + p) // 2) % p, block_size, p):
155
+ block[t] = False
156
+ for idx, p in enumerate(block):
157
+ if p:
158
+ yield a + 2 * idx + 1
159
+ a += 2 * block_size
160
+
161
+ def extend_to_no(self, i):
162
+ """Extend to include the ith prime number.
163
+
164
+ Parameters
165
+ ==========
166
+
167
+ i : integer
168
+
169
+ Examples
170
+ ========
171
+
172
+ >>> from sympy import sieve
173
+ >>> sieve._reset() # this line for doctest only
174
+ >>> sieve.extend_to_no(9)
175
+ >>> sieve._list
176
+ array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
177
+
178
+ Notes
179
+ =====
180
+
181
+ The list is extended by 50% if it is too short, so it is
182
+ likely that it will be longer than requested.
183
+ """
184
+ i = as_int(i)
185
+ while len(self._list) < i:
186
+ self.extend(int(self._list[-1] * 1.5))
187
+
188
+ def primerange(self, a, b=None):
189
+ """Generate all prime numbers in the range [2, a) or [a, b).
190
+
191
+ Examples
192
+ ========
193
+
194
+ >>> from sympy import sieve, prime
195
+
196
+ All primes less than 19:
197
+
198
+ >>> print([i for i in sieve.primerange(19)])
199
+ [2, 3, 5, 7, 11, 13, 17]
200
+
201
+ All primes greater than or equal to 7 and less than 19:
202
+
203
+ >>> print([i for i in sieve.primerange(7, 19)])
204
+ [7, 11, 13, 17]
205
+
206
+ All primes through the 10th prime
207
+
208
+ >>> list(sieve.primerange(prime(10) + 1))
209
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
210
+
211
+ """
212
+ if b is None:
213
+ b = _as_int_ceiling(a)
214
+ a = 2
215
+ else:
216
+ a = max(2, _as_int_ceiling(a))
217
+ b = _as_int_ceiling(b)
218
+ if a >= b:
219
+ return
220
+ self.extend(b)
221
+ yield from self._list[bisect_left(self._list, a):
222
+ bisect_left(self._list, b)]
223
+
224
+ def totientrange(self, a, b):
225
+ """Generate all totient numbers for the range [a, b).
226
+
227
+ Examples
228
+ ========
229
+
230
+ >>> from sympy import sieve
231
+ >>> print([i for i in sieve.totientrange(7, 18)])
232
+ [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
233
+ """
234
+ a = max(1, _as_int_ceiling(a))
235
+ b = _as_int_ceiling(b)
236
+ n = len(self._tlist)
237
+ if a >= b:
238
+ return
239
+ elif b <= n:
240
+ for i in range(a, b):
241
+ yield self._tlist[i]
242
+ else:
243
+ self._tlist += _array('L', range(n, b))
244
+ for i in range(1, n):
245
+ ti = self._tlist[i]
246
+ if ti == i - 1:
247
+ startindex = (n + i - 1) // i * i
248
+ for j in range(startindex, b, i):
249
+ self._tlist[j] -= self._tlist[j] // i
250
+ if i >= a:
251
+ yield ti
252
+
253
+ for i in range(n, b):
254
+ ti = self._tlist[i]
255
+ if ti == i:
256
+ for j in range(i, b, i):
257
+ self._tlist[j] -= self._tlist[j] // i
258
+ if i >= a:
259
+ yield self._tlist[i]
260
+
261
+ def mobiusrange(self, a, b):
262
+ """Generate all mobius numbers for the range [a, b).
263
+
264
+ Parameters
265
+ ==========
266
+
267
+ a : integer
268
+ First number in range
269
+
270
+ b : integer
271
+ First number outside of range
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import sieve
277
+ >>> print([i for i in sieve.mobiusrange(7, 18)])
278
+ [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
279
+ """
280
+ a = max(1, _as_int_ceiling(a))
281
+ b = _as_int_ceiling(b)
282
+ n = len(self._mlist)
283
+ if a >= b:
284
+ return
285
+ elif b <= n:
286
+ for i in range(a, b):
287
+ yield self._mlist[i]
288
+ else:
289
+ self._mlist += _array('i', [0]*(b - n))
290
+ for i in range(1, n):
291
+ mi = self._mlist[i]
292
+ startindex = (n + i - 1) // i * i
293
+ for j in range(startindex, b, i):
294
+ self._mlist[j] -= mi
295
+ if i >= a:
296
+ yield mi
297
+
298
+ for i in range(n, b):
299
+ mi = self._mlist[i]
300
+ for j in range(2 * i, b, i):
301
+ self._mlist[j] -= mi
302
+ if i >= a:
303
+ yield mi
304
+
305
+ def search(self, n):
306
+ """Return the indices i, j of the primes that bound n.
307
+
308
+ If n is prime then i == j.
309
+
310
+ Although n can be an expression, if ceiling cannot convert
311
+ it to an integer then an n error will be raised.
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import sieve
317
+ >>> sieve.search(25)
318
+ (9, 10)
319
+ >>> sieve.search(23)
320
+ (9, 9)
321
+ """
322
+ test = _as_int_ceiling(n)
323
+ n = as_int(n)
324
+ if n < 2:
325
+ raise ValueError("n should be >= 2 but got: %s" % n)
326
+ if n > self._list[-1]:
327
+ self.extend(n)
328
+ b = bisect(self._list, n)
329
+ if self._list[b - 1] == test:
330
+ return b, b
331
+ else:
332
+ return b, b + 1
333
+
334
+ def __contains__(self, n):
335
+ try:
336
+ n = as_int(n)
337
+ assert n >= 2
338
+ except (ValueError, AssertionError):
339
+ return False
340
+ if n % 2 == 0:
341
+ return n == 2
342
+ a, b = self.search(n)
343
+ return a == b
344
+
345
+ def __iter__(self):
346
+ for n in count(1):
347
+ yield self[n]
348
+
349
+ def __getitem__(self, n):
350
+ """Return the nth prime number"""
351
+ if isinstance(n, slice):
352
+ self.extend_to_no(n.stop)
353
+ start = n.start if n.start is not None else 0
354
+ if start < 1:
355
+ # sieve[:5] would be empty (starting at -1), let's
356
+ # just be explicit and raise.
357
+ raise IndexError("Sieve indices start at 1.")
358
+ return self._list[start - 1:n.stop - 1:n.step]
359
+ else:
360
+ if n < 1:
361
+ # offset is one, so forbid explicit access to sieve[0]
362
+ # (would surprisingly return the last one).
363
+ raise IndexError("Sieve indices start at 1.")
364
+ n = as_int(n)
365
+ self.extend_to_no(n)
366
+ return self._list[n - 1]
367
+
368
+ # Generate a global object for repeated use in trial division etc
369
+ sieve = Sieve()
370
+
371
+ def prime(nth):
372
+ r"""
373
+ Return the nth prime number, where primes are indexed starting from 1:
374
+ prime(1) = 2, prime(2) = 3, etc.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ nth : int
380
+ The position of the prime number to return (must be a positive integer).
381
+
382
+ Returns
383
+ =======
384
+
385
+ int
386
+ The nth prime number.
387
+
388
+ Examples
389
+ ========
390
+
391
+ >>> from sympy import prime
392
+ >>> prime(10)
393
+ 29
394
+ >>> prime(1)
395
+ 2
396
+ >>> prime(100000)
397
+ 1299709
398
+
399
+ See Also
400
+ ========
401
+
402
+ sympy.ntheory.primetest.isprime : Test if a number is prime.
403
+ primerange : Generate all primes in a given range.
404
+ primepi : Return the number of primes less than or equal to a given number.
405
+
406
+ References
407
+ ==========
408
+
409
+ .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem
410
+ .. [2] https://en.wikipedia.org/wiki/Logarithmic_integral_function
411
+ .. [3] https://en.wikipedia.org/wiki/Skewes%27_number
412
+ """
413
+ n = as_int(nth)
414
+ if n < 1:
415
+ raise ValueError("nth must be a positive integer; prime(1) == 2")
416
+
417
+ # Check if n is within the sieve range
418
+ if n <= len(sieve._list):
419
+ return sieve[n]
420
+
421
+ from sympy.functions.elementary.exponential import log
422
+ from sympy.functions.special.error_functions import li
423
+
424
+ if n < 1000:
425
+ # Extend sieve up to 8*n as this is empirically sufficient
426
+ sieve.extend(8 * n)
427
+ return sieve[n]
428
+
429
+ a = 2
430
+ # Estimate an upper bound for the nth prime using the prime number theorem
431
+ b = int(n * (log(n).evalf() + log(log(n)).evalf()))
432
+
433
+ # Binary search for the least m such that li(m) > n
434
+ while a < b:
435
+ mid = (a + b) >> 1
436
+ if li(mid).evalf() > n:
437
+ b = mid
438
+ else:
439
+ a = mid + 1
440
+
441
+ return nextprime(a - 1, n - _primepi(a - 1))
442
+
443
+
444
+ @deprecated("""\
445
+ The `sympy.ntheory.generate.primepi` has been moved to `sympy.functions.combinatorial.numbers.primepi`.""",
446
+ deprecated_since_version="1.13",
447
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
448
+ def primepi(n):
449
+ r""" Represents the prime counting function pi(n) = the number
450
+ of prime numbers less than or equal to n.
451
+
452
+ .. deprecated:: 1.13
453
+
454
+ The ``primepi`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primepi`
455
+ instead. See its documentation for more information. See
456
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
457
+
458
+ Algorithm Description:
459
+
460
+ In sieve method, we remove all multiples of prime p
461
+ except p itself.
462
+
463
+ Let phi(i,j) be the number of integers 2 <= k <= i
464
+ which remain after sieving from primes less than
465
+ or equal to j.
466
+ Clearly, pi(n) = phi(n, sqrt(n))
467
+
468
+ If j is not a prime,
469
+ phi(i,j) = phi(i, j - 1)
470
+
471
+ if j is a prime,
472
+ We remove all numbers(except j) whose
473
+ smallest prime factor is j.
474
+
475
+ Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
476
+ Now, after sieving from primes $\le j - 1$,
477
+ a must remain
478
+ (because x, and hence a has no prime factor $\le j - 1$)
479
+ Clearly, there are phi(i / j, j - 1) such a
480
+ which remain on sieving from primes $\le j - 1$
481
+
482
+ Now, if a is a prime less than equal to j - 1,
483
+ $x= j \times a$ has smallest prime factor = a, and
484
+ has already been removed(by sieving from a).
485
+ So, we do not need to remove it again.
486
+ (Note: there will be pi(j - 1) such x)
487
+
488
+ Thus, number of x, that will be removed are:
489
+ phi(i / j, j - 1) - phi(j - 1, j - 1)
490
+ (Note that pi(j - 1) = phi(j - 1, j - 1))
491
+
492
+ $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
493
+
494
+ So,following recursion is used and implemented as dp:
495
+
496
+ phi(a, b) = phi(a, b - 1), if b is not a prime
497
+ phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
498
+
499
+ Clearly a is always of the form floor(n / k),
500
+ which can take at most $2\sqrt{n}$ values.
501
+ Two arrays arr1,arr2 are maintained
502
+ arr1[i] = phi(i, j),
503
+ arr2[i] = phi(n // i, j)
504
+
505
+ Finally the answer is arr2[1]
506
+
507
+ Examples
508
+ ========
509
+
510
+ >>> from sympy import primepi, prime, prevprime, isprime
511
+ >>> primepi(25)
512
+ 9
513
+
514
+ So there are 9 primes less than or equal to 25. Is 25 prime?
515
+
516
+ >>> isprime(25)
517
+ False
518
+
519
+ It is not. So the first prime less than 25 must be the
520
+ 9th prime:
521
+
522
+ >>> prevprime(25) == prime(9)
523
+ True
524
+
525
+ See Also
526
+ ========
527
+
528
+ sympy.ntheory.primetest.isprime : Test if n is prime
529
+ primerange : Generate all primes in a given range
530
+ prime : Return the nth prime
531
+ """
532
+ from sympy.functions.combinatorial.numbers import primepi as func_primepi
533
+ return func_primepi(n)
534
+
535
+
536
+ def _primepi(n:int) -> int:
537
+ r""" Represents the prime counting function pi(n) = the number
538
+ of prime numbers less than or equal to n.
539
+
540
+ Explanation
541
+ ===========
542
+
543
+ In sieve method, we remove all multiples of prime p
544
+ except p itself.
545
+
546
+ Let phi(i,j) be the number of integers 2 <= k <= i
547
+ which remain after sieving from primes less than
548
+ or equal to j.
549
+ Clearly, pi(n) = phi(n, sqrt(n))
550
+
551
+ If j is not a prime,
552
+ phi(i,j) = phi(i, j - 1)
553
+
554
+ if j is a prime,
555
+ We remove all numbers(except j) whose
556
+ smallest prime factor is j.
557
+
558
+ Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
559
+ Now, after sieving from primes $\le j - 1$,
560
+ a must remain
561
+ (because x, and hence a has no prime factor $\le j - 1$)
562
+ Clearly, there are phi(i / j, j - 1) such a
563
+ which remain on sieving from primes $\le j - 1$
564
+
565
+ Now, if a is a prime less than equal to j - 1,
566
+ $x= j \times a$ has smallest prime factor = a, and
567
+ has already been removed(by sieving from a).
568
+ So, we do not need to remove it again.
569
+ (Note: there will be pi(j - 1) such x)
570
+
571
+ Thus, number of x, that will be removed are:
572
+ phi(i / j, j - 1) - phi(j - 1, j - 1)
573
+ (Note that pi(j - 1) = phi(j - 1, j - 1))
574
+
575
+ $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
576
+
577
+ So,following recursion is used and implemented as dp:
578
+
579
+ phi(a, b) = phi(a, b - 1), if b is not a prime
580
+ phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
581
+
582
+ Clearly a is always of the form floor(n / k),
583
+ which can take at most $2\sqrt{n}$ values.
584
+ Two arrays arr1,arr2 are maintained
585
+ arr1[i] = phi(i, j),
586
+ arr2[i] = phi(n // i, j)
587
+
588
+ Finally the answer is arr2[1]
589
+
590
+ Parameters
591
+ ==========
592
+
593
+ n : int
594
+
595
+ """
596
+ if n < 2:
597
+ return 0
598
+ if n <= sieve._list[-1]:
599
+ return sieve.search(n)[0]
600
+ lim = sqrt(n)
601
+ arr1 = [(i + 1) >> 1 for i in range(lim + 1)]
602
+ arr2 = [0] + [(n//i + 1) >> 1 for i in range(1, lim + 1)]
603
+ skip = [False] * (lim + 1)
604
+ for i in range(3, lim + 1, 2):
605
+ # Presently, arr1[k]=phi(k,i - 1),
606
+ # arr2[k] = phi(n // k,i - 1) # not all k's do this
607
+ if skip[i]:
608
+ # skip if i is a composite number
609
+ continue
610
+ p = arr1[i - 1]
611
+ for j in range(i, lim + 1, i):
612
+ skip[j] = True
613
+ # update arr2
614
+ # phi(n/j, i) = phi(n/j, i-1) - phi(n/(i*j), i-1) + phi(i-1, i-1)
615
+ for j in range(1, min(n // (i * i), lim) + 1, 2):
616
+ # No need for arr2[j] in j such that skip[j] is True to
617
+ # compute the final required arr2[1].
618
+ if skip[j]:
619
+ continue
620
+ st = i * j
621
+ if st <= lim:
622
+ arr2[j] -= arr2[st] - p
623
+ else:
624
+ arr2[j] -= arr1[n // st] - p
625
+ # update arr1
626
+ # phi(j, i) = phi(j, i-1) - phi(j/i, i-1) + phi(i-1, i-1)
627
+ # where the range below i**2 is fixed and
628
+ # does not need to be calculated.
629
+ for j in range(lim, min(lim, i*i - 1), -1):
630
+ arr1[j] -= arr1[j // i] - p
631
+ return arr2[1]
632
+
633
+
634
+ def nextprime(n, ith=1):
635
+ """ Return the ith prime greater than n.
636
+
637
+ Parameters
638
+ ==========
639
+
640
+ n : integer
641
+ ith : positive integer
642
+
643
+ Returns
644
+ =======
645
+
646
+ int : Return the ith prime greater than n
647
+
648
+ Raises
649
+ ======
650
+
651
+ ValueError
652
+ If ``ith <= 0``.
653
+ If ``n`` or ``ith`` is not an integer.
654
+
655
+ Notes
656
+ =====
657
+
658
+ Potential primes are located at 6*j +/- 1. This
659
+ property is used during searching.
660
+
661
+ >>> from sympy import nextprime
662
+ >>> [(i, nextprime(i)) for i in range(10, 15)]
663
+ [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
664
+ >>> nextprime(2, ith=2) # the 2nd prime after 2
665
+ 5
666
+
667
+ See Also
668
+ ========
669
+
670
+ prevprime : Return the largest prime smaller than n
671
+ primerange : Generate all primes in a given range
672
+
673
+ """
674
+ n = int(n)
675
+ i = as_int(ith)
676
+ if i <= 0:
677
+ raise ValueError("ith should be positive")
678
+ if n < 2:
679
+ n = 2
680
+ i -= 1
681
+ if n <= sieve._list[-2]:
682
+ l, _ = sieve.search(n)
683
+ if l + i - 1 < len(sieve._list):
684
+ return sieve._list[l + i - 1]
685
+ n = sieve._list[-1]
686
+ i += l - len(sieve._list)
687
+ nn = 6*(n//6)
688
+ if nn == n:
689
+ n += 1
690
+ if isprime(n):
691
+ i -= 1
692
+ if not i:
693
+ return n
694
+ n += 4
695
+ elif n - nn == 5:
696
+ n += 2
697
+ if isprime(n):
698
+ i -= 1
699
+ if not i:
700
+ return n
701
+ n += 4
702
+ else:
703
+ n = nn + 5
704
+ while 1:
705
+ if isprime(n):
706
+ i -= 1
707
+ if not i:
708
+ return n
709
+ n += 2
710
+ if isprime(n):
711
+ i -= 1
712
+ if not i:
713
+ return n
714
+ n += 4
715
+
716
+
717
+ def prevprime(n):
718
+ """ Return the largest prime smaller than n.
719
+
720
+ Notes
721
+ =====
722
+
723
+ Potential primes are located at 6*j +/- 1. This
724
+ property is used during searching.
725
+
726
+ >>> from sympy import prevprime
727
+ >>> [(i, prevprime(i)) for i in range(10, 15)]
728
+ [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
729
+
730
+ See Also
731
+ ========
732
+
733
+ nextprime : Return the ith prime greater than n
734
+ primerange : Generates all primes in a given range
735
+ """
736
+ n = _as_int_ceiling(n)
737
+ if n < 3:
738
+ raise ValueError("no preceding primes")
739
+ if n < 8:
740
+ return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
741
+ if n <= sieve._list[-1]:
742
+ l, u = sieve.search(n)
743
+ if l == u:
744
+ return sieve[l-1]
745
+ else:
746
+ return sieve[l]
747
+ nn = 6*(n//6)
748
+ if n - nn <= 1:
749
+ n = nn - 1
750
+ if isprime(n):
751
+ return n
752
+ n -= 4
753
+ else:
754
+ n = nn + 1
755
+ while 1:
756
+ if isprime(n):
757
+ return n
758
+ n -= 2
759
+ if isprime(n):
760
+ return n
761
+ n -= 4
762
+
763
+
764
+ def primerange(a, b=None):
765
+ """ Generate a list of all prime numbers in the range [2, a),
766
+ or [a, b).
767
+
768
+ If the range exists in the default sieve, the values will
769
+ be returned from there; otherwise values will be returned
770
+ but will not modify the sieve.
771
+
772
+ Examples
773
+ ========
774
+
775
+ >>> from sympy import primerange, prime
776
+
777
+ All primes less than 19:
778
+
779
+ >>> list(primerange(19))
780
+ [2, 3, 5, 7, 11, 13, 17]
781
+
782
+ All primes greater than or equal to 7 and less than 19:
783
+
784
+ >>> list(primerange(7, 19))
785
+ [7, 11, 13, 17]
786
+
787
+ All primes through the 10th prime
788
+
789
+ >>> list(primerange(prime(10) + 1))
790
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
791
+
792
+ The Sieve method, primerange, is generally faster but it will
793
+ occupy more memory as the sieve stores values. The default
794
+ instance of Sieve, named sieve, can be used:
795
+
796
+ >>> from sympy import sieve
797
+ >>> list(sieve.primerange(1, 30))
798
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
799
+
800
+ Notes
801
+ =====
802
+
803
+ Some famous conjectures about the occurrence of primes in a given
804
+ range are [1]:
805
+
806
+ - Twin primes: though often not, the following will give 2 primes
807
+ an infinite number of times:
808
+ primerange(6*n - 1, 6*n + 2)
809
+ - Legendre's: the following always yields at least one prime
810
+ primerange(n**2, (n+1)**2+1)
811
+ - Bertrand's (proven): there is always a prime in the range
812
+ primerange(n, 2*n)
813
+ - Brocard's: there are at least four primes in the range
814
+ primerange(prime(n)**2, prime(n+1)**2)
815
+
816
+ The average gap between primes is log(n) [2]; the gap between
817
+ primes can be arbitrarily large since sequences of composite
818
+ numbers are arbitrarily large, e.g. the numbers in the sequence
819
+ n! + 2, n! + 3 ... n! + n are all composite.
820
+
821
+ See Also
822
+ ========
823
+
824
+ prime : Return the nth prime
825
+ nextprime : Return the ith prime greater than n
826
+ prevprime : Return the largest prime smaller than n
827
+ randprime : Returns a random prime in a given range
828
+ primorial : Returns the product of primes based on condition
829
+ Sieve.primerange : return range from already computed primes
830
+ or extend the sieve to contain the requested
831
+ range.
832
+
833
+ References
834
+ ==========
835
+
836
+ .. [1] https://en.wikipedia.org/wiki/Prime_number
837
+ .. [2] https://primes.utm.edu/notes/gaps.html
838
+ """
839
+ if b is None:
840
+ a, b = 2, a
841
+ if a >= b:
842
+ return
843
+ # If we already have the range, return it.
844
+ largest_known_prime = sieve._list[-1]
845
+ if b <= largest_known_prime:
846
+ yield from sieve.primerange(a, b)
847
+ return
848
+ # If we know some of it, return it.
849
+ if a <= largest_known_prime:
850
+ yield from sieve._list[bisect_left(sieve._list, a):]
851
+ a = largest_known_prime + 1
852
+ elif a % 2:
853
+ a -= 1
854
+ tail = min(b, (largest_known_prime)**2)
855
+ if a < tail:
856
+ yield from sieve._primerange(a, tail)
857
+ a = tail
858
+ if b <= a:
859
+ return
860
+ # otherwise compute, without storing, the desired range.
861
+ while 1:
862
+ a = nextprime(a)
863
+ if a < b:
864
+ yield a
865
+ else:
866
+ return
867
+
868
+
869
+ def randprime(a, b):
870
+ """ Return a random prime number in the range [a, b).
871
+
872
+ Bertrand's postulate assures that
873
+ randprime(a, 2*a) will always succeed for a > 1.
874
+
875
+ Note that due to implementation difficulties,
876
+ the prime numbers chosen are not uniformly random.
877
+ For example, there are two primes in the range [112, 128),
878
+ ``113`` and ``127``, but ``randprime(112, 128)`` returns ``127``
879
+ with a probability of 15/17.
880
+
881
+ Examples
882
+ ========
883
+
884
+ >>> from sympy import randprime, isprime
885
+ >>> randprime(1, 30) #doctest: +SKIP
886
+ 13
887
+ >>> isprime(randprime(1, 30))
888
+ True
889
+
890
+ See Also
891
+ ========
892
+
893
+ primerange : Generate all primes in a given range
894
+
895
+ References
896
+ ==========
897
+
898
+ .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
899
+
900
+ """
901
+ if a >= b:
902
+ return
903
+ a, b = map(int, (a, b))
904
+ n = randint(a - 1, b)
905
+ p = nextprime(n)
906
+ if p >= b:
907
+ p = prevprime(b)
908
+ if p < a:
909
+ raise ValueError("no primes exist in the specified range")
910
+ return p
911
+
912
+
913
+ def primorial(n, nth=True):
914
+ """
915
+ Returns the product of the first n primes (default) or
916
+ the primes less than or equal to n (when ``nth=False``).
917
+
918
+ Examples
919
+ ========
920
+
921
+ >>> from sympy.ntheory.generate import primorial, primerange
922
+ >>> from sympy import factorint, Mul, primefactors, sqrt
923
+ >>> primorial(4) # the first 4 primes are 2, 3, 5, 7
924
+ 210
925
+ >>> primorial(4, nth=False) # primes <= 4 are 2 and 3
926
+ 6
927
+ >>> primorial(1)
928
+ 2
929
+ >>> primorial(1, nth=False)
930
+ 1
931
+ >>> primorial(sqrt(101), nth=False)
932
+ 210
933
+
934
+ One can argue that the primes are infinite since if you take
935
+ a set of primes and multiply them together (e.g. the primorial) and
936
+ then add or subtract 1, the result cannot be divided by any of the
937
+ original factors, hence either 1 or more new primes must divide this
938
+ product of primes.
939
+
940
+ In this case, the number itself is a new prime:
941
+
942
+ >>> factorint(primorial(4) + 1)
943
+ {211: 1}
944
+
945
+ In this case two new primes are the factors:
946
+
947
+ >>> factorint(primorial(4) - 1)
948
+ {11: 1, 19: 1}
949
+
950
+ Here, some primes smaller and larger than the primes multiplied together
951
+ are obtained:
952
+
953
+ >>> p = list(primerange(10, 20))
954
+ >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
955
+ [2, 5, 31, 149]
956
+
957
+ See Also
958
+ ========
959
+
960
+ primerange : Generate all primes in a given range
961
+
962
+ """
963
+ if nth:
964
+ n = as_int(n)
965
+ else:
966
+ n = int(n)
967
+ if n < 1:
968
+ raise ValueError("primorial argument must be >= 1")
969
+ p = 1
970
+ if nth:
971
+ for i in range(1, n + 1):
972
+ p *= prime(i)
973
+ else:
974
+ for i in primerange(2, n + 1):
975
+ p *= i
976
+ return p
977
+
978
+
979
+ def cycle_length(f, x0, nmax=None, values=False):
980
+ """For a given iterated sequence, return a generator that gives
981
+ the length of the iterated cycle (lambda) and the length of terms
982
+ before the cycle begins (mu); if ``values`` is True then the
983
+ terms of the sequence will be returned instead. The sequence is
984
+ started with value ``x0``.
985
+
986
+ Note: more than the first lambda + mu terms may be returned and this
987
+ is the cost of cycle detection with Brent's method; there are, however,
988
+ generally less terms calculated than would have been calculated if the
989
+ proper ending point were determined, e.g. by using Floyd's method.
990
+
991
+ >>> from sympy.ntheory.generate import cycle_length
992
+
993
+ This will yield successive values of i <-- func(i):
994
+
995
+ >>> def gen(func, i):
996
+ ... while 1:
997
+ ... yield i
998
+ ... i = func(i)
999
+ ...
1000
+
1001
+ A function is defined:
1002
+
1003
+ >>> func = lambda i: (i**2 + 1) % 51
1004
+
1005
+ and given a seed of 4 and the mu and lambda terms calculated:
1006
+
1007
+ >>> next(cycle_length(func, 4))
1008
+ (6, 3)
1009
+
1010
+ We can see what is meant by looking at the output:
1011
+
1012
+ >>> iter = cycle_length(func, 4, values=True)
1013
+ >>> list(iter)
1014
+ [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
1015
+
1016
+ There are 6 repeating values after the first 3.
1017
+
1018
+ If a sequence is suspected of being longer than you might wish, ``nmax``
1019
+ can be used to exit early (and mu will be returned as None):
1020
+
1021
+ >>> next(cycle_length(func, 4, nmax = 4))
1022
+ (4, None)
1023
+ >>> list(cycle_length(func, 4, nmax = 4, values=True))
1024
+ [4, 17, 35, 2]
1025
+
1026
+ Code modified from:
1027
+ https://en.wikipedia.org/wiki/Cycle_detection.
1028
+ """
1029
+
1030
+ nmax = int(nmax or 0)
1031
+
1032
+ # main phase: search successive powers of two
1033
+ power = lam = 1
1034
+ tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
1035
+ i = 1
1036
+ if values:
1037
+ yield tortoise
1038
+ while tortoise != hare and (not nmax or i < nmax):
1039
+ i += 1
1040
+ if power == lam: # time to start a new power of two?
1041
+ tortoise = hare
1042
+ power *= 2
1043
+ lam = 0
1044
+ if values:
1045
+ yield hare
1046
+ hare = f(hare)
1047
+ lam += 1
1048
+ if nmax and i == nmax:
1049
+ if values:
1050
+ return
1051
+ else:
1052
+ yield nmax, None
1053
+ return
1054
+ if not values:
1055
+ # Find the position of the first repetition of length lambda
1056
+ mu = 0
1057
+ tortoise = hare = x0
1058
+ for i in range(lam):
1059
+ hare = f(hare)
1060
+ while tortoise != hare:
1061
+ tortoise = f(tortoise)
1062
+ hare = f(hare)
1063
+ mu += 1
1064
+ yield lam, mu
1065
+
1066
+
1067
+ def composite(nth):
1068
+ """ Return the nth composite number, with the composite numbers indexed as
1069
+ composite(1) = 4, composite(2) = 6, etc....
1070
+
1071
+ Examples
1072
+ ========
1073
+
1074
+ >>> from sympy import composite
1075
+ >>> composite(36)
1076
+ 52
1077
+ >>> composite(1)
1078
+ 4
1079
+ >>> composite(17737)
1080
+ 20000
1081
+
1082
+ See Also
1083
+ ========
1084
+
1085
+ sympy.ntheory.primetest.isprime : Test if n is prime
1086
+ primerange : Generate all primes in a given range
1087
+ primepi : Return the number of primes less than or equal to n
1088
+ prime : Return the nth prime
1089
+ compositepi : Return the number of positive composite numbers less than or equal to n
1090
+ """
1091
+ n = as_int(nth)
1092
+ if n < 1:
1093
+ raise ValueError("nth must be a positive integer; composite(1) == 4")
1094
+ composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
1095
+ if n <= 10:
1096
+ return composite_arr[n - 1]
1097
+
1098
+ a, b = 4, sieve._list[-1]
1099
+ if n <= b - _primepi(b) - 1:
1100
+ while a < b - 1:
1101
+ mid = (a + b) >> 1
1102
+ if mid - _primepi(mid) - 1 > n:
1103
+ b = mid
1104
+ else:
1105
+ a = mid
1106
+ if isprime(a):
1107
+ a -= 1
1108
+ return a
1109
+
1110
+ from sympy.functions.elementary.exponential import log
1111
+ from sympy.functions.special.error_functions import li
1112
+ a = 4 # Lower bound for binary search
1113
+ b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
1114
+
1115
+ while a < b:
1116
+ mid = (a + b) >> 1
1117
+ if mid - li(mid) - 1 > n:
1118
+ b = mid
1119
+ else:
1120
+ a = mid + 1
1121
+
1122
+ n_composites = a - _primepi(a) - 1
1123
+ while n_composites > n:
1124
+ if not isprime(a):
1125
+ n_composites -= 1
1126
+ a -= 1
1127
+ if isprime(a):
1128
+ a -= 1
1129
+ return a
1130
+
1131
+
1132
+ def compositepi(n):
1133
+ """ Return the number of positive composite numbers less than or equal to n.
1134
+ The first positive composite is 4, i.e. compositepi(4) = 1.
1135
+
1136
+ Examples
1137
+ ========
1138
+
1139
+ >>> from sympy import compositepi
1140
+ >>> compositepi(25)
1141
+ 15
1142
+ >>> compositepi(1000)
1143
+ 831
1144
+
1145
+ See Also
1146
+ ========
1147
+
1148
+ sympy.ntheory.primetest.isprime : Test if n is prime
1149
+ primerange : Generate all primes in a given range
1150
+ prime : Return the nth prime
1151
+ primepi : Return the number of primes less than or equal to n
1152
+ composite : Return the nth composite number
1153
+ """
1154
+ n = int(n)
1155
+ if n < 4:
1156
+ return 0
1157
+ return n - _primepi(n) - 1
.venv/lib/python3.12/site-packages/sympy/ntheory/modular.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.external.gmpy import gcd, gcdext
4
+ from sympy.ntheory.primetest import isprime
5
+ from sympy.polys.domains import ZZ
6
+ from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
7
+ from sympy.utilities.misc import as_int
8
+
9
+
10
+ def symmetric_residue(a, m):
11
+ """Return the residual mod m such that it is within half of the modulus.
12
+
13
+ >>> from sympy.ntheory.modular import symmetric_residue
14
+ >>> symmetric_residue(1, 6)
15
+ 1
16
+ >>> symmetric_residue(4, 6)
17
+ -2
18
+ """
19
+ if a <= m // 2:
20
+ return a
21
+ return a - m
22
+
23
+
24
+ def crt(m, v, symmetric=False, check=True):
25
+ r"""Chinese Remainder Theorem.
26
+
27
+ The moduli in m are assumed to be pairwise coprime. The output
28
+ is then an integer f, such that f = v_i mod m_i for each pair out
29
+ of v and m. If ``symmetric`` is False a positive integer will be
30
+ returned, else \|f\| will be less than or equal to the LCM of the
31
+ moduli, and thus f may be negative.
32
+
33
+ If the moduli are not co-prime the correct result will be returned
34
+ if/when the test of the result is found to be incorrect. This result
35
+ will be None if there is no solution.
36
+
37
+ The keyword ``check`` can be set to False if it is known that the moduli
38
+ are coprime.
39
+
40
+ Examples
41
+ ========
42
+
43
+ As an example consider a set of residues ``U = [49, 76, 65]``
44
+ and a set of moduli ``M = [99, 97, 95]``. Then we have::
45
+
46
+ >>> from sympy.ntheory.modular import crt
47
+
48
+ >>> crt([99, 97, 95], [49, 76, 65])
49
+ (639985, 912285)
50
+
51
+ This is the correct result because::
52
+
53
+ >>> [639985 % m for m in [99, 97, 95]]
54
+ [49, 76, 65]
55
+
56
+ If the moduli are not co-prime, you may receive an incorrect result
57
+ if you use ``check=False``:
58
+
59
+ >>> crt([12, 6, 17], [3, 4, 2], check=False)
60
+ (954, 1224)
61
+ >>> [954 % m for m in [12, 6, 17]]
62
+ [6, 0, 2]
63
+ >>> crt([12, 6, 17], [3, 4, 2]) is None
64
+ True
65
+ >>> crt([3, 6], [2, 5])
66
+ (5, 6)
67
+
68
+ Note: the order of gf_crt's arguments is reversed relative to crt,
69
+ and that solve_congruence takes residue, modulus pairs.
70
+
71
+ Programmer's note: rather than checking that all pairs of moduli share
72
+ no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
73
+ that there is no factor in common, a check that the result gives the
74
+ indicated residuals is performed -- an O(n) operation.
75
+
76
+ See Also
77
+ ========
78
+
79
+ solve_congruence
80
+ sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
81
+ """
82
+ if check:
83
+ m = list(map(as_int, m))
84
+ v = list(map(as_int, v))
85
+
86
+ result = gf_crt(v, m, ZZ)
87
+ mm = prod(m)
88
+
89
+ if check:
90
+ if not all(v % m == result % m for v, m in zip(v, m)):
91
+ result = solve_congruence(*list(zip(v, m)),
92
+ check=False, symmetric=symmetric)
93
+ if result is None:
94
+ return result
95
+ result, mm = result
96
+
97
+ if symmetric:
98
+ return int(symmetric_residue(result, mm)), int(mm)
99
+ return int(result), int(mm)
100
+
101
+
102
+ def crt1(m):
103
+ """First part of Chinese Remainder Theorem, for multiple application.
104
+
105
+ Examples
106
+ ========
107
+
108
+ >>> from sympy.ntheory.modular import crt, crt1, crt2
109
+ >>> m = [99, 97, 95]
110
+ >>> v = [49, 76, 65]
111
+
112
+ The following two codes have the same result.
113
+
114
+ >>> crt(m, v)
115
+ (639985, 912285)
116
+
117
+ >>> mm, e, s = crt1(m)
118
+ >>> crt2(m, v, mm, e, s)
119
+ (639985, 912285)
120
+
121
+ However, it is faster when we want to fix ``m`` and
122
+ compute for multiple ``v``, i.e. the following cases:
123
+
124
+ >>> mm, e, s = crt1(m)
125
+ >>> vs = [[52, 21, 37], [19, 46, 76]]
126
+ >>> for v in vs:
127
+ ... print(crt2(m, v, mm, e, s))
128
+ (397042, 912285)
129
+ (803206, 912285)
130
+
131
+ See Also
132
+ ========
133
+
134
+ sympy.polys.galoistools.gf_crt1 : low level crt routine used by this routine
135
+ sympy.ntheory.modular.crt
136
+ sympy.ntheory.modular.crt2
137
+
138
+ """
139
+
140
+ return gf_crt1(m, ZZ)
141
+
142
+
143
+ def crt2(m, v, mm, e, s, symmetric=False):
144
+ """Second part of Chinese Remainder Theorem, for multiple application.
145
+
146
+ See ``crt1`` for usage.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.ntheory.modular import crt1, crt2
152
+ >>> mm, e, s = crt1([18, 42, 6])
153
+ >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
154
+ (0, 4536)
155
+
156
+ See Also
157
+ ========
158
+
159
+ sympy.polys.galoistools.gf_crt2 : low level crt routine used by this routine
160
+ sympy.ntheory.modular.crt
161
+ sympy.ntheory.modular.crt1
162
+
163
+ """
164
+
165
+ result = gf_crt2(v, m, mm, e, s, ZZ)
166
+
167
+ if symmetric:
168
+ return int(symmetric_residue(result, mm)), int(mm)
169
+ return int(result), int(mm)
170
+
171
+
172
+ def solve_congruence(*remainder_modulus_pairs, **hint):
173
+ """Compute the integer ``n`` that has the residual ``ai`` when it is
174
+ divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
175
+ this function: ((a1, m1), (a2, m2), ...). If there is no solution,
176
+ return None. Otherwise return ``n`` and its modulus.
177
+
178
+ The ``mi`` values need not be co-prime. If it is known that the moduli are
179
+ not co-prime then the hint ``check`` can be set to False (default=True) and
180
+ the check for a quicker solution via crt() (valid when the moduli are
181
+ co-prime) will be skipped.
182
+
183
+ If the hint ``symmetric`` is True (default is False), the value of ``n``
184
+ will be within 1/2 of the modulus, possibly negative.
185
+
186
+ Examples
187
+ ========
188
+
189
+ >>> from sympy.ntheory.modular import solve_congruence
190
+
191
+ What number is 2 mod 3, 3 mod 5 and 2 mod 7?
192
+
193
+ >>> solve_congruence((2, 3), (3, 5), (2, 7))
194
+ (23, 105)
195
+ >>> [23 % m for m in [3, 5, 7]]
196
+ [2, 3, 2]
197
+
198
+ If you prefer to work with all remainder in one list and
199
+ all moduli in another, send the arguments like this:
200
+
201
+ >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
202
+ (23, 105)
203
+
204
+ The moduli need not be co-prime; in this case there may or
205
+ may not be a solution:
206
+
207
+ >>> solve_congruence((2, 3), (4, 6)) is None
208
+ True
209
+
210
+ >>> solve_congruence((2, 3), (5, 6))
211
+ (5, 6)
212
+
213
+ The symmetric flag will make the result be within 1/2 of the modulus:
214
+
215
+ >>> solve_congruence((2, 3), (5, 6), symmetric=True)
216
+ (-1, 6)
217
+
218
+ See Also
219
+ ========
220
+
221
+ crt : high level routine implementing the Chinese Remainder Theorem
222
+
223
+ """
224
+ def combine(c1, c2):
225
+ """Return the tuple (a, m) which satisfies the requirement
226
+ that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
227
+
228
+ References
229
+ ==========
230
+
231
+ .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution
232
+ """
233
+ a1, m1 = c1
234
+ a2, m2 = c2
235
+ a, b, c = m1, a2 - a1, m2
236
+ g = gcd(a, b, c)
237
+ a, b, c = [i//g for i in [a, b, c]]
238
+ if a != 1:
239
+ g, inv_a, _ = gcdext(a, c)
240
+ if g != 1:
241
+ return None
242
+ b *= inv_a
243
+ a, m = a1 + m1*b, m1*c
244
+ return a, m
245
+
246
+ rm = remainder_modulus_pairs
247
+ symmetric = hint.get('symmetric', False)
248
+
249
+ if hint.get('check', True):
250
+ rm = [(as_int(r), as_int(m)) for r, m in rm]
251
+
252
+ # ignore redundant pairs but raise an error otherwise; also
253
+ # make sure that a unique set of bases is sent to gf_crt if
254
+ # they are all prime.
255
+ #
256
+ # The routine will work out less-trivial violations and
257
+ # return None, e.g. for the pairs (1,3) and (14,42) there
258
+ # is no answer because 14 mod 42 (having a gcd of 14) implies
259
+ # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
260
+ # which, being 0 mod 3, is inconsistent with 1 mod 3. But to
261
+ # preprocess the input beyond checking of another pair with 42
262
+ # or 3 as the modulus (for this example) is not necessary.
263
+ uniq = {}
264
+ for r, m in rm:
265
+ r %= m
266
+ if m in uniq:
267
+ if r != uniq[m]:
268
+ return None
269
+ continue
270
+ uniq[m] = r
271
+ rm = [(r, m) for m, r in uniq.items()]
272
+ del uniq
273
+
274
+ # if the moduli are co-prime, the crt will be significantly faster;
275
+ # checking all pairs for being co-prime gets to be slow but a prime
276
+ # test is a good trade-off
277
+ if all(isprime(m) for r, m in rm):
278
+ r, m = list(zip(*rm))
279
+ return crt(m, r, symmetric=symmetric, check=False)
280
+
281
+ rv = (0, 1)
282
+ for rmi in rm:
283
+ rv = combine(rv, rmi)
284
+ if rv is None:
285
+ break
286
+ n, m = rv
287
+ n = n % m
288
+ else:
289
+ if symmetric:
290
+ return symmetric_residue(n, m), m
291
+ return n, m
.venv/lib/python3.12/site-packages/sympy/ntheory/multinomial.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities.misc import as_int
2
+
3
+
4
+ def binomial_coefficients(n):
5
+ """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
6
+ :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
7
+
8
+ Examples
9
+ ========
10
+
11
+ >>> from sympy.ntheory import binomial_coefficients
12
+ >>> binomial_coefficients(9)
13
+ {(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
14
+ (4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
15
+
16
+ See Also
17
+ ========
18
+
19
+ binomial_coefficients_list, multinomial_coefficients
20
+ """
21
+ n = as_int(n)
22
+ d = {(0, n): 1, (n, 0): 1}
23
+ a = 1
24
+ for k in range(1, n//2 + 1):
25
+ a = (a * (n - k + 1))//k
26
+ d[k, n - k] = d[n - k, k] = a
27
+ return d
28
+
29
+
30
+ def binomial_coefficients_list(n):
31
+ """ Return a list of binomial coefficients as rows of the Pascal's
32
+ triangle.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy.ntheory import binomial_coefficients_list
38
+ >>> binomial_coefficients_list(9)
39
+ [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
40
+
41
+ See Also
42
+ ========
43
+
44
+ binomial_coefficients, multinomial_coefficients
45
+ """
46
+ n = as_int(n)
47
+ d = [1] * (n + 1)
48
+ a = 1
49
+ for k in range(1, n//2 + 1):
50
+ a = (a * (n - k + 1))//k
51
+ d[k] = d[n - k] = a
52
+ return d
53
+
54
+
55
+ def multinomial_coefficients(m, n):
56
+ r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
57
+ where ``C_kn`` are multinomial coefficients such that
58
+ ``n=k1+k2+..+km``.
59
+
60
+ Examples
61
+ ========
62
+
63
+ >>> from sympy.ntheory import multinomial_coefficients
64
+ >>> multinomial_coefficients(2, 5) # indirect doctest
65
+ {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
66
+
67
+ Notes
68
+ =====
69
+
70
+ The algorithm is based on the following result:
71
+
72
+ .. math::
73
+ \binom{n}{k_1, \ldots, k_m} =
74
+ \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
75
+
76
+ Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
77
+ of the author.
78
+
79
+ See Also
80
+ ========
81
+
82
+ binomial_coefficients_list, binomial_coefficients
83
+ """
84
+ m = as_int(m)
85
+ n = as_int(n)
86
+ if not m:
87
+ if n:
88
+ return {}
89
+ return {(): 1}
90
+ if m == 2:
91
+ return binomial_coefficients(n)
92
+ if m >= 2*n and n > 1:
93
+ return dict(multinomial_coefficients_iterator(m, n))
94
+ t = [n] + [0] * (m - 1)
95
+ r = {tuple(t): 1}
96
+ if n:
97
+ j = 0 # j will be the leftmost nonzero position
98
+ else:
99
+ j = m
100
+ # enumerate tuples in co-lex order
101
+ while j < m - 1:
102
+ # compute next tuple
103
+ tj = t[j]
104
+ if j:
105
+ t[j] = 0
106
+ t[0] = tj
107
+ if tj > 1:
108
+ t[j + 1] += 1
109
+ j = 0
110
+ start = 1
111
+ v = 0
112
+ else:
113
+ j += 1
114
+ start = j + 1
115
+ v = r[tuple(t)]
116
+ t[j] += 1
117
+ # compute the value
118
+ # NB: the initialization of v was done above
119
+ for k in range(start, m):
120
+ if t[k]:
121
+ t[k] -= 1
122
+ v += r[tuple(t)]
123
+ t[k] += 1
124
+ t[0] -= 1
125
+ r[tuple(t)] = (v * tj) // (n - t[0])
126
+ return r
127
+
128
+
129
+ def multinomial_coefficients_iterator(m, n, _tuple=tuple):
130
+ """multinomial coefficient iterator
131
+
132
+ This routine has been optimized for `m` large with respect to `n` by taking
133
+ advantage of the fact that when the monomial tuples `t` are stripped of
134
+ zeros, their coefficient is the same as that of the monomial tuples from
135
+ ``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
136
+ precomputed to save memory and time.
137
+
138
+ >>> from sympy.ntheory.multinomial import multinomial_coefficients
139
+ >>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
140
+ >>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
141
+ True
142
+
143
+ Examples
144
+ ========
145
+
146
+ >>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
147
+ >>> it = multinomial_coefficients_iterator(20,3)
148
+ >>> next(it)
149
+ ((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
150
+ """
151
+ m = as_int(m)
152
+ n = as_int(n)
153
+ if m < 2*n or n == 1:
154
+ mc = multinomial_coefficients(m, n)
155
+ yield from mc.items()
156
+ else:
157
+ mc = multinomial_coefficients(n, n)
158
+ mc1 = {}
159
+ for k, v in mc.items():
160
+ mc1[_tuple(filter(None, k))] = v
161
+ mc = mc1
162
+
163
+ t = [n] + [0] * (m - 1)
164
+ t1 = _tuple(t)
165
+ b = _tuple(filter(None, t1))
166
+ yield (t1, mc[b])
167
+ if n:
168
+ j = 0 # j will be the leftmost nonzero position
169
+ else:
170
+ j = m
171
+ # enumerate tuples in co-lex order
172
+ while j < m - 1:
173
+ # compute next tuple
174
+ tj = t[j]
175
+ if j:
176
+ t[j] = 0
177
+ t[0] = tj
178
+ if tj > 1:
179
+ t[j + 1] += 1
180
+ j = 0
181
+ else:
182
+ j += 1
183
+ t[j] += 1
184
+
185
+ t[0] -= 1
186
+ t1 = _tuple(t)
187
+ b = _tuple(filter(None, t1))
188
+ yield (t1, mc[b])
.venv/lib/python3.12/site-packages/sympy/ntheory/partitions_.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mpmath.libmp import (fzero, from_int, from_rational,
2
+ fone, fhalf, bitcount, to_int, mpf_mul, mpf_div, mpf_sub,
3
+ mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
4
+ from .residue_ntheory import _sqrt_mod_prime_power, is_quad_residue
5
+ from sympy.utilities.decorator import deprecated
6
+ from sympy.utilities.memoization import recurrence_memo
7
+
8
+ import math
9
+ from itertools import count
10
+
11
+ def _pre():
12
+ maxn = 10**5
13
+ global _factor, _totient
14
+ _factor = [0]*maxn
15
+ _totient = [1]*maxn
16
+ lim = int(maxn**0.5) + 5
17
+ for i in range(2, lim):
18
+ if _factor[i] == 0:
19
+ for j in range(i*i, maxn, i):
20
+ if _factor[j] == 0:
21
+ _factor[j] = i
22
+ for i in range(2, maxn):
23
+ if _factor[i] == 0:
24
+ _factor[i] = i
25
+ _totient[i] = i-1
26
+ continue
27
+ x = _factor[i]
28
+ y = i//x
29
+ if y % x == 0:
30
+ _totient[i] = _totient[y]*x
31
+ else:
32
+ _totient[i] = _totient[y]*(x - 1)
33
+
34
+ def _a(n, k, prec):
35
+ """ Compute the inner sum in HRR formula [1]_
36
+
37
+ References
38
+ ==========
39
+
40
+ .. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
41
+
42
+ """
43
+ if k == 1:
44
+ return fone
45
+
46
+ k1 = k
47
+ e = 0
48
+ p = _factor[k]
49
+ while k1 % p == 0:
50
+ k1 //= p
51
+ e += 1
52
+ k2 = k//k1 # k2 = p^e
53
+ v = 1 - 24*n
54
+ pi = mpf_pi(prec)
55
+
56
+ if k1 == 1:
57
+ # k = p^e
58
+ if p == 2:
59
+ mod = 8*k
60
+ v = mod + v % mod
61
+ v = (v*pow(9, k - 1, mod)) % mod
62
+ m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
63
+ arg = mpf_div(mpf_mul(
64
+ from_int(4*m), pi, prec), from_int(mod), prec)
65
+ return mpf_mul(mpf_mul(
66
+ from_int((-1)**e*(2 - (m % 4))),
67
+ mpf_sqrt(from_int(k), prec), prec),
68
+ mpf_sin(arg, prec), prec)
69
+ if p == 3:
70
+ mod = 3*k
71
+ v = mod + v % mod
72
+ if e > 1:
73
+ v = (v*pow(64, k//3 - 1, mod)) % mod
74
+ m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
75
+ arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
76
+ from_int(mod), prec)
77
+ return mpf_mul(mpf_mul(
78
+ from_int(2*(-1)**(e + 1)*(3 - 2*(m % 3))),
79
+ mpf_sqrt(from_int(k//3), prec), prec),
80
+ mpf_sin(arg, prec), prec)
81
+ v = k + v % k
82
+ jacobi3 = -1 if k % 12 in [5, 7] else 1
83
+ if v % p == 0:
84
+ if e == 1:
85
+ return mpf_mul(
86
+ from_int(jacobi3),
87
+ mpf_sqrt(from_int(k), prec), prec)
88
+ return fzero
89
+ if not is_quad_residue(v, p):
90
+ return fzero
91
+ _phi = p**(e - 1)*(p - 1)
92
+ v = (v*pow(576, _phi - 1, k))
93
+ m = _sqrt_mod_prime_power(v, p, e)[0]
94
+ arg = mpf_div(
95
+ mpf_mul(from_int(4*m), pi, prec),
96
+ from_int(k), prec)
97
+ return mpf_mul(mpf_mul(
98
+ from_int(2*jacobi3),
99
+ mpf_sqrt(from_int(k), prec), prec),
100
+ mpf_cos(arg, prec), prec)
101
+
102
+ if p != 2 or e >= 3:
103
+ d1, d2 = math.gcd(k1, 24), math.gcd(k2, 24)
104
+ e = 24//(d1*d2)
105
+ n1 = ((d2*e*n + (k2**2 - 1)//d1)*
106
+ pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
107
+ n2 = ((d1*e*n + (k1**2 - 1)//d2)*
108
+ pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
109
+ return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
110
+ if e == 2:
111
+ n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
112
+ n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
113
+ return mpf_mul(mpf_mul(
114
+ from_int(-1),
115
+ _a(n1, k1, prec), prec),
116
+ _a(n2, k2, prec))
117
+ n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
118
+ n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
119
+ return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
120
+
121
+ def _d(n, j, prec, sq23pi, sqrt8):
122
+ """
123
+ Compute the sinh term in the outer sum of the HRR formula.
124
+ The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
125
+ """
126
+ j = from_int(j)
127
+ pi = mpf_pi(prec)
128
+ a = mpf_div(sq23pi, j, prec)
129
+ b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
130
+ c = mpf_sqrt(b, prec)
131
+ ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
132
+ D = mpf_div(
133
+ mpf_sqrt(j, prec),
134
+ mpf_mul(mpf_mul(sqrt8, b), pi), prec)
135
+ E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
136
+ return mpf_mul(D, E)
137
+
138
+
139
+ @recurrence_memo([1, 1])
140
+ def _partition_rec(n: int, prev) -> int:
141
+ """ Calculate the partition function P(n)
142
+
143
+ Parameters
144
+ ==========
145
+
146
+ n : int
147
+ nonnegative integer
148
+
149
+ """
150
+ v = 0
151
+ penta = 0 # pentagonal number: 1, 5, 12, ...
152
+ for i in count():
153
+ penta += 3*i + 1
154
+ np = n - penta
155
+ if np < 0:
156
+ break
157
+ s = prev[np]
158
+ np -= i + 1
159
+ # np = n - gp where gp = generalized pentagonal: 2, 7, 15, ...
160
+ if 0 <= np:
161
+ s += prev[np]
162
+ v += -s if i % 2 else s
163
+ return v
164
+
165
+
166
+ def _partition(n: int) -> int:
167
+ """ Calculate the partition function P(n)
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ n : int
173
+
174
+ """
175
+ if n < 0:
176
+ return 0
177
+ if (n <= 200_000 and n - _partition_rec.cache_length() < 70 or
178
+ _partition_rec.cache_length() == 2 and n < 14_400):
179
+ # There will be 2*10**5 elements created here
180
+ # and n elements created by partition, so in case we
181
+ # are going to be working with small n, we just
182
+ # use partition to calculate (and cache) the values
183
+ # since lookup is used there while summation, using
184
+ # _factor and _totient, will be used below. But we
185
+ # only do so if n is relatively close to the length
186
+ # of the cache since doing 1 calculation here is about
187
+ # the same as adding 70 elements to the cache. In addition,
188
+ # the startup here costs about the same as calculating the first
189
+ # 14,400 values via partition, so we delay startup here unless n
190
+ # is smaller than that.
191
+ return _partition_rec(n)
192
+ if '_factor' not in globals():
193
+ _pre()
194
+ # Estimate number of bits in p(n). This formula could be tidied
195
+ pbits = int((
196
+ math.pi*(2*n/3.)**0.5 -
197
+ math.log(4*n))/math.log(10) + 1) * \
198
+ math.log2(10)
199
+ prec = p = int(pbits*1.1 + 100)
200
+
201
+ # find the number of terms needed so rounded sum will be accurate
202
+ # using Rademacher's bound M(n, N) for the remainder after a partial
203
+ # sum of N terms (https://arxiv.org/pdf/1205.5991.pdf, (1.8))
204
+ c1 = 44*math.pi**2/(225*math.sqrt(3))
205
+ c2 = math.pi*math.sqrt(2)/75
206
+ c3 = math.pi*math.sqrt(2/3)
207
+ def _M(n, N):
208
+ sqrt = math.sqrt
209
+ return c1/sqrt(N) + c2*sqrt(N/(n - 1))*math.sinh(c3*sqrt(n)/N)
210
+ big = max(9, math.ceil(n**0.5)) # should be too large (for n > 65, ceil should work)
211
+ assert _M(n, big) < 0.5 # else double big until too large
212
+ while big > 40 and _M(n, big) < 0.5:
213
+ big //= 2
214
+ small = big
215
+ big = small*2
216
+ while big - small > 1:
217
+ N = (big + small)//2
218
+ if (er := _M(n, N)) < 0.5:
219
+ big = N
220
+ elif er >= 0.5:
221
+ small = N
222
+ M = big # done with function M; now have value
223
+
224
+ # sanity check for expected size of answer
225
+ if M > 10**5: # i.e. M > maxn
226
+ raise ValueError("Input too big") # i.e. n > 149832547102
227
+
228
+ # calculate it
229
+ s = fzero
230
+ sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
231
+ sqrt8 = mpf_sqrt(from_int(8), p)
232
+ for q in range(1, M):
233
+ a = _a(n, q, p)
234
+ d = _d(n, q, p, sq23pi, sqrt8)
235
+ s = mpf_add(s, mpf_mul(a, d), prec)
236
+ # On average, the terms decrease rapidly in magnitude.
237
+ # Dynamically reducing the precision greatly improves
238
+ # performance.
239
+ p = bitcount(abs(to_int(d))) + 50
240
+ return int(to_int(mpf_add(s, fhalf, prec)))
241
+
242
+
243
+ @deprecated("""\
244
+ The `sympy.ntheory.partitions_.npartitions` has been moved to `sympy.functions.combinatorial.numbers.partition`.""",
245
+ deprecated_since_version="1.13",
246
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
247
+ def npartitions(n, verbose=False):
248
+ """
249
+ Calculate the partition function P(n), i.e. the number of ways that
250
+ n can be written as a sum of positive integers.
251
+
252
+ .. deprecated:: 1.13
253
+
254
+ The ``npartitions`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.partition`
255
+ instead. See its documentation for more information. See
256
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
257
+
258
+ P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
259
+
260
+
261
+ The correctness of this implementation has been tested through $10^{10}$.
262
+
263
+ Examples
264
+ ========
265
+
266
+ >>> from sympy.functions.combinatorial.numbers import partition
267
+ >>> partition(25)
268
+ 1958
269
+
270
+ References
271
+ ==========
272
+
273
+ .. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
274
+
275
+ """
276
+ from sympy.functions.combinatorial.numbers import partition as func_partition
277
+ return func_partition(n)
.venv/lib/python3.12/site-packages/sympy/ntheory/primetest.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Primality testing
3
+
4
+ """
5
+
6
+ from itertools import count
7
+
8
+ from sympy.core.sympify import sympify
9
+ from sympy.external.gmpy import (gmpy as _gmpy, gcd, jacobi,
10
+ is_square as gmpy_is_square,
11
+ bit_scan1, is_fermat_prp, is_euler_prp,
12
+ is_selfridge_prp, is_strong_selfridge_prp,
13
+ is_strong_bpsw_prp)
14
+ from sympy.external.ntheory import _lucas_sequence
15
+ from sympy.utilities.misc import as_int, filldedent
16
+
17
+ # Note: This list should be updated whenever new Mersenne primes are found.
18
+ # Refer: https://www.mersenne.org/
19
+ MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
20
+ 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
21
+ 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
22
+ 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933,
23
+ 136279841)
24
+
25
+
26
+ def is_fermat_pseudoprime(n, a):
27
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
28
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
29
+
30
+ .. math ::
31
+ a^{n-1} \equiv 1 \pmod{n}
32
+
33
+ (where mod refers to the modulo operation).
34
+
35
+ Parameters
36
+ ==========
37
+
38
+ n : Integer
39
+ ``n`` is a positive integer.
40
+ a : Integer
41
+ ``a`` is a positive integer.
42
+ ``a`` and ``n`` should be relatively prime.
43
+
44
+ Returns
45
+ =======
46
+
47
+ bool : If ``n`` is prime, it always returns ``True``.
48
+ The composite number that returns ``True`` is called an Fermat pseudoprime.
49
+
50
+ Examples
51
+ ========
52
+
53
+ >>> from sympy.ntheory.primetest import is_fermat_pseudoprime
54
+ >>> from sympy.ntheory.factor_ import isprime
55
+ >>> for n in range(1, 1000):
56
+ ... if is_fermat_pseudoprime(n, 2) and not isprime(n):
57
+ ... print(n)
58
+ 341
59
+ 561
60
+ 645
61
+
62
+ References
63
+ ==========
64
+
65
+ .. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
66
+ """
67
+ n, a = as_int(n), as_int(a)
68
+ if a == 1:
69
+ return n == 2 or bool(n % 2)
70
+ return is_fermat_prp(n, a)
71
+
72
+
73
+ def is_euler_pseudoprime(n, a):
74
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
75
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
76
+
77
+ .. math ::
78
+ a^{(n-1)/2} \equiv \pm 1 \pmod{n}
79
+
80
+ (where mod refers to the modulo operation).
81
+
82
+ Parameters
83
+ ==========
84
+
85
+ n : Integer
86
+ ``n`` is a positive integer.
87
+ a : Integer
88
+ ``a`` is a positive integer.
89
+ ``a`` and ``n`` should be relatively prime.
90
+
91
+ Returns
92
+ =======
93
+
94
+ bool : If ``n`` is prime, it always returns ``True``.
95
+ The composite number that returns ``True`` is called an Euler pseudoprime.
96
+
97
+ Examples
98
+ ========
99
+
100
+ >>> from sympy.ntheory.primetest import is_euler_pseudoprime
101
+ >>> from sympy.ntheory.factor_ import isprime
102
+ >>> for n in range(1, 1000):
103
+ ... if is_euler_pseudoprime(n, 2) and not isprime(n):
104
+ ... print(n)
105
+ 341
106
+ 561
107
+
108
+ References
109
+ ==========
110
+
111
+ .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
112
+ """
113
+ n, a = as_int(n), as_int(a)
114
+ if a < 1:
115
+ raise ValueError("a should be an integer greater than 0")
116
+ if n < 1:
117
+ raise ValueError("n should be an integer greater than 0")
118
+ if n == 1:
119
+ return False
120
+ if a == 1:
121
+ return n == 2 or bool(n % 2) # (prime or odd composite)
122
+ if n % 2 == 0:
123
+ return n == 2
124
+ if gcd(n, a) != 1:
125
+ raise ValueError("The two numbers should be relatively prime")
126
+ return pow(a, (n - 1) // 2, n) in [1, n - 1]
127
+
128
+
129
+ def is_euler_jacobi_pseudoprime(n, a):
130
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
131
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
132
+
133
+ .. math ::
134
+ a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}
135
+
136
+ (where mod refers to the modulo operation).
137
+
138
+ Parameters
139
+ ==========
140
+
141
+ n : Integer
142
+ ``n`` is a positive integer.
143
+ a : Integer
144
+ ``a`` is a positive integer.
145
+ ``a`` and ``n`` should be relatively prime.
146
+
147
+ Returns
148
+ =======
149
+
150
+ bool : If ``n`` is prime, it always returns ``True``.
151
+ The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.
152
+
153
+ Examples
154
+ ========
155
+
156
+ >>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
157
+ >>> from sympy.ntheory.factor_ import isprime
158
+ >>> for n in range(1, 1000):
159
+ ... if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
160
+ ... print(n)
161
+ 561
162
+
163
+ References
164
+ ==========
165
+
166
+ .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
167
+ """
168
+ n, a = as_int(n), as_int(a)
169
+ if a == 1:
170
+ return n == 2 or bool(n % 2)
171
+ return is_euler_prp(n, a)
172
+
173
+
174
+ def is_square(n, prep=True):
175
+ """Return True if n == a * a for some integer a, else False.
176
+ If n is suspected of *not* being a square then this is a
177
+ quick method of confirming that it is not.
178
+
179
+ Examples
180
+ ========
181
+
182
+ >>> from sympy.ntheory.primetest import is_square
183
+ >>> is_square(25)
184
+ True
185
+ >>> is_square(2)
186
+ False
187
+
188
+ References
189
+ ==========
190
+
191
+ .. [1] https://mersenneforum.org/showpost.php?p=110896
192
+
193
+ See Also
194
+ ========
195
+ sympy.core.intfunc.isqrt
196
+ """
197
+ if prep:
198
+ n = as_int(n)
199
+ if n < 0:
200
+ return False
201
+ if n in (0, 1):
202
+ return True
203
+ return gmpy_is_square(n)
204
+
205
+
206
+ def _test(n, base, s, t):
207
+ """Miller-Rabin strong pseudoprime test for one base.
208
+ Return False if n is definitely composite, True if n is
209
+ probably prime, with a probability greater than 3/4.
210
+
211
+ """
212
+ # do the Fermat test
213
+ b = pow(base, t, n)
214
+ if b == 1 or b == n - 1:
215
+ return True
216
+ for _ in range(s - 1):
217
+ b = pow(b, 2, n)
218
+ if b == n - 1:
219
+ return True
220
+ # see I. Niven et al. "An Introduction to Theory of Numbers", page 78
221
+ if b == 1:
222
+ return False
223
+ return False
224
+
225
+
226
+ def mr(n, bases):
227
+ """Perform a Miller-Rabin strong pseudoprime test on n using a
228
+ given list of bases/witnesses.
229
+
230
+ References
231
+ ==========
232
+
233
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
234
+ A Computational Perspective", Springer, 2nd edition, 135-138
235
+
236
+ A list of thresholds and the bases they require are here:
237
+ https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy.ntheory.primetest import mr
243
+ >>> mr(1373651, [2, 3])
244
+ False
245
+ >>> mr(479001599, [31, 73])
246
+ True
247
+
248
+ """
249
+ from sympy.polys.domains import ZZ
250
+
251
+ n = as_int(n)
252
+ if n < 2 or (n > 2 and n % 2 == 0):
253
+ return False
254
+ # remove powers of 2 from n-1 (= t * 2**s)
255
+ s = bit_scan1(n - 1)
256
+ t = n >> s
257
+ for base in bases:
258
+ # Bases >= n are wrapped, bases < 2 are invalid
259
+ if base >= n:
260
+ base %= n
261
+ if base >= 2:
262
+ base = ZZ(base)
263
+ if not _test(n, base, s, t):
264
+ return False
265
+ return True
266
+
267
+
268
+ def _lucas_extrastrong_params(n):
269
+ """Calculates the "extra strong" parameters (D, P, Q) for n.
270
+
271
+ Parameters
272
+ ==========
273
+
274
+ n : int
275
+ positive odd integer
276
+
277
+ Returns
278
+ =======
279
+
280
+ D, P, Q: "extra strong" parameters.
281
+ ``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy.ntheory.primetest import _lucas_extrastrong_params
287
+ >>> _lucas_extrastrong_params(101)
288
+ (12, 4, 1)
289
+ >>> _lucas_extrastrong_params(15)
290
+ (0, 0, 0)
291
+
292
+ References
293
+ ==========
294
+ .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
295
+ https://oeis.org/A217719
296
+ .. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime
297
+
298
+ """
299
+ for P in count(3):
300
+ D = P**2 - 4
301
+ j = jacobi(D, n)
302
+ if j == -1:
303
+ return (D, P, 1)
304
+ elif j == 0 and D % n:
305
+ return (0, 0, 0)
306
+
307
+
308
+ def is_lucas_prp(n):
309
+ """Standard Lucas compositeness test with Selfridge parameters. Returns
310
+ False if n is definitely composite, and True if n is a Lucas probable
311
+ prime.
312
+
313
+ This is typically used in combination with the Miller-Rabin test.
314
+
315
+ References
316
+ ==========
317
+ .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
318
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
319
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
320
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
321
+ .. [2] OEIS A217120: Lucas Pseudoprimes
322
+ https://oeis.org/A217120
323
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
329
+ >>> for i in range(10000):
330
+ ... if is_lucas_prp(i) and not isprime(i):
331
+ ... print(i)
332
+ 323
333
+ 377
334
+ 1159
335
+ 1829
336
+ 3827
337
+ 5459
338
+ 5777
339
+ 9071
340
+ 9179
341
+ """
342
+ n = as_int(n)
343
+ if n < 2:
344
+ return False
345
+ return is_selfridge_prp(n)
346
+
347
+
348
+ def is_strong_lucas_prp(n):
349
+ """Strong Lucas compositeness test with Selfridge parameters. Returns
350
+ False if n is definitely composite, and True if n is a strong Lucas
351
+ probable prime.
352
+
353
+ This is often used in combination with the Miller-Rabin test, and
354
+ in particular, when combined with M-R base 2 creates the strong BPSW test.
355
+
356
+ References
357
+ ==========
358
+ .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
359
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
360
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
361
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
362
+ .. [2] OEIS A217255: Strong Lucas Pseudoprimes
363
+ https://oeis.org/A217255
364
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
365
+ .. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
366
+
367
+ Examples
368
+ ========
369
+
370
+ >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
371
+ >>> for i in range(20000):
372
+ ... if is_strong_lucas_prp(i) and not isprime(i):
373
+ ... print(i)
374
+ 5459
375
+ 5777
376
+ 10877
377
+ 16109
378
+ 18971
379
+ """
380
+ n = as_int(n)
381
+ if n < 2:
382
+ return False
383
+ return is_strong_selfridge_prp(n)
384
+
385
+
386
+ def is_extra_strong_lucas_prp(n):
387
+ """Extra Strong Lucas compositeness test. Returns False if n is
388
+ definitely composite, and True if n is an "extra strong" Lucas probable
389
+ prime.
390
+
391
+ The parameters are selected using P = 3, Q = 1, then incrementing P until
392
+ (D|n) == -1. The test itself is as defined in [1]_, from the
393
+ Mo and Jones preprint. The parameter selection and test are the same as
394
+ used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
395
+ page on Wikipedia.
396
+
397
+ It is 20-50% faster than the strong test.
398
+
399
+ Because of the different parameters selected, there is no relationship
400
+ between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
401
+ In particular, one is not a subset of the other.
402
+
403
+ References
404
+ ==========
405
+ .. [1] Jon Grantham, Frobenius Pseudoprimes,
406
+ Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
407
+ https://doi.org/10.1090%2FS0025-5718-00-01197-2
408
+ .. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
409
+ https://oeis.org/A217719
410
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
411
+
412
+ Examples
413
+ ========
414
+
415
+ >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
416
+ >>> for i in range(20000):
417
+ ... if is_extra_strong_lucas_prp(i) and not isprime(i):
418
+ ... print(i)
419
+ 989
420
+ 3239
421
+ 5777
422
+ 10877
423
+ """
424
+ # Implementation notes:
425
+ # 1) the parameters differ from Thomas R. Nicely's. His parameter
426
+ # selection leads to pseudoprimes that overlap M-R tests, and
427
+ # contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
428
+ # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
429
+ # sequence must have Q=1. See Grantham theorem 2.3, any of the
430
+ # references on the MathWorld page, or run it and see Q=-1 is wrong.
431
+ n = as_int(n)
432
+ if n == 2:
433
+ return True
434
+ if n < 2 or (n % 2) == 0:
435
+ return False
436
+ if gmpy_is_square(n):
437
+ return False
438
+
439
+ D, P, Q = _lucas_extrastrong_params(n)
440
+ if D == 0:
441
+ return False
442
+
443
+ # remove powers of 2 from n+1 (= k * 2**s)
444
+ s = bit_scan1(n + 1)
445
+ k = (n + 1) >> s
446
+
447
+ U, V, _ = _lucas_sequence(n, P, Q, k)
448
+
449
+ if U == 0 and (V == 2 or V == n - 2):
450
+ return True
451
+ for _ in range(1, s):
452
+ if V == 0:
453
+ return True
454
+ V = (V*V - 2) % n
455
+ return False
456
+
457
+
458
+ def proth_test(n):
459
+ r""" Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.
460
+
461
+ Parameters
462
+ ==========
463
+
464
+ n : Integer
465
+ ``n`` is Proth number
466
+
467
+ Returns
468
+ =======
469
+
470
+ bool : If ``True``, then ``n`` is the Proth prime
471
+
472
+ Raises
473
+ ======
474
+
475
+ ValueError
476
+ If ``n`` is not Proth number.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy.ntheory.primetest import proth_test
482
+ >>> proth_test(41)
483
+ True
484
+ >>> proth_test(57)
485
+ False
486
+
487
+ References
488
+ ==========
489
+
490
+ .. [1] https://en.wikipedia.org/wiki/Proth_prime
491
+
492
+ """
493
+ n = as_int(n)
494
+ if n < 3:
495
+ raise ValueError("n is not Proth number")
496
+ m = bit_scan1(n - 1)
497
+ k = n >> m
498
+ if m < k.bit_length():
499
+ raise ValueError("n is not Proth number")
500
+ if n % 3 == 0:
501
+ return n == 3
502
+ if k % 3: # n % 12 == 5
503
+ return pow(3, n >> 1, n) == n - 1
504
+ # If `n` is a square number, then `jacobi(a, n) = 1` for any `a`
505
+ if gmpy_is_square(n):
506
+ return False
507
+ # `a` may be chosen at random.
508
+ # In any case, we want to find `a` such that `jacobi(a, n) = -1`.
509
+ for a in range(5, n):
510
+ j = jacobi(a, n)
511
+ if j == -1:
512
+ return pow(a, n >> 1, n) == n - 1
513
+ if j == 0:
514
+ return False
515
+
516
+
517
+ def _lucas_lehmer_primality_test(p):
518
+ r""" Test if the Mersenne number `M_p = 2^p-1` is prime.
519
+
520
+ Parameters
521
+ ==========
522
+
523
+ p : int
524
+ ``p`` is an odd prime number
525
+
526
+ Returns
527
+ =======
528
+
529
+ bool : If ``True``, then `M_p` is the Mersenne prime
530
+
531
+ Examples
532
+ ========
533
+
534
+ >>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
535
+ >>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
536
+ True
537
+ >>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
538
+ False
539
+
540
+ See Also
541
+ ========
542
+
543
+ is_mersenne_prime
544
+
545
+ References
546
+ ==========
547
+
548
+ .. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
549
+
550
+ """
551
+ v = 4
552
+ m = 2**p - 1
553
+ for _ in range(p - 2):
554
+ v = pow(v, 2, m) - 2
555
+ return v == 0
556
+
557
+
558
+ def is_mersenne_prime(n):
559
+ """Returns True if ``n`` is a Mersenne prime, else False.
560
+
561
+ A Mersenne prime is a prime number having the form `2^i - 1`.
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy.ntheory.factor_ import is_mersenne_prime
567
+ >>> is_mersenne_prime(6)
568
+ False
569
+ >>> is_mersenne_prime(127)
570
+ True
571
+
572
+ References
573
+ ==========
574
+
575
+ .. [1] https://mathworld.wolfram.com/MersennePrime.html
576
+
577
+ """
578
+ n = as_int(n)
579
+ if n < 1:
580
+ return False
581
+ if n & (n + 1):
582
+ # n is not Mersenne number
583
+ return False
584
+ p = n.bit_length()
585
+ if p in MERSENNE_PRIME_EXPONENTS:
586
+ return True
587
+ if p < 65_000_000 or not isprime(p):
588
+ # According to GIMPS, verification was completed on September 19, 2023 for p less than 65 million.
589
+ # https://www.mersenne.org/report_milestones/
590
+ # If p is composite number, then n=2**p-1 is composite number.
591
+ return False
592
+ result = _lucas_lehmer_primality_test(p)
593
+ if result:
594
+ raise ValueError(filldedent('''
595
+ This Mersenne Prime, 2^%s - 1, should
596
+ be added to SymPy's known values.''' % p))
597
+ return result
598
+
599
+
600
+ _MR_BASES_32 = [15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295,
601
+ 2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471,
602
+ 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763,
603
+ 4852, 5012, 3185, 1333, 6227,5298, 1074, 2391, 5113, 7061,
604
+ 803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556,
605
+ 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373,
606
+ 6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467,
607
+ 3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888,
608
+ 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875,
609
+ 3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165,
610
+ 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377,
611
+ 1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601,
612
+ 6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360,
613
+ 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031,
614
+ 2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725,
615
+ 3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371,
616
+ 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727,
617
+ 3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126,
618
+ 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674,
619
+ 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007,
620
+ 35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521,
621
+ 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166,
622
+ 1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197,
623
+ 13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449,
624
+ 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194]
625
+
626
+
627
+ def isprime(n):
628
+ """
629
+ Test if n is a prime number (True) or not (False). For n < 2^64 the
630
+ answer is definitive; larger n values have a small probability of actually
631
+ being pseudoprimes.
632
+
633
+ Negative numbers (e.g. -2) are not considered prime.
634
+
635
+ The first step is looking for trivial factors, which if found enables
636
+ a quick return. Next, if the sieve is large enough, use bisection search
637
+ on the sieve. For small numbers, a set of deterministic Miller-Rabin
638
+ tests are performed with bases that are known to have no counterexamples
639
+ in their range. Finally if the number is larger than 2^64, a strong
640
+ BPSW test is performed. While this is a probable prime test and we
641
+ believe counterexamples exist, there are no known counterexamples.
642
+
643
+ Examples
644
+ ========
645
+
646
+ >>> from sympy.ntheory import isprime
647
+ >>> isprime(13)
648
+ True
649
+ >>> isprime(15)
650
+ False
651
+
652
+ Notes
653
+ =====
654
+
655
+ This routine is intended only for integer input, not numerical
656
+ expressions which may represent numbers. Floats are also
657
+ rejected as input because they represent numbers of limited
658
+ precision. While it is tempting to permit 7.0 to represent an
659
+ integer there are errors that may "pass silently" if this is
660
+ allowed:
661
+
662
+ >>> from sympy import Float, S
663
+ >>> int(1e3) == 1e3 == 10**3
664
+ True
665
+ >>> int(1e23) == 1e23
666
+ True
667
+ >>> int(1e23) == 10**23
668
+ False
669
+
670
+ >>> near_int = 1 + S(1)/10**19
671
+ >>> near_int == int(near_int)
672
+ False
673
+ >>> n = Float(near_int, 10) # truncated by precision
674
+ >>> n % 1 == 0
675
+ True
676
+ >>> n = Float(near_int, 20)
677
+ >>> n % 1 == 0
678
+ False
679
+
680
+ See Also
681
+ ========
682
+
683
+ sympy.ntheory.generate.primerange : Generates all primes in a given range
684
+ sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
685
+ sympy.ntheory.generate.prime : Return the nth prime
686
+
687
+ References
688
+ ==========
689
+ .. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
690
+ .. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
691
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
692
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
693
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
694
+ .. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
695
+ """
696
+ n = as_int(n)
697
+
698
+ # Step 1, do quick composite testing via trial division. The individual
699
+ # modulo tests benchmark faster than one or two primorial igcds for me.
700
+ # The point here is just to speedily handle small numbers and many
701
+ # composites. Step 2 only requires that n <= 2 get handled here.
702
+ if n in [2, 3, 5]:
703
+ return True
704
+ if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
705
+ return False
706
+ if n < 49:
707
+ return True
708
+ if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
709
+ (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
710
+ (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
711
+ return False
712
+ if n < 2809:
713
+ return True
714
+ if n < 65077:
715
+ # There are only five Euler pseudoprimes with a least prime factor greater than 47
716
+ return pow(2, n >> 1, n) in [1, n - 1] and n not in [8321, 31621, 42799, 49141, 49981]
717
+
718
+ # bisection search on the sieve if the sieve is large enough
719
+ from sympy.ntheory.generate import sieve as s
720
+ if n <= s._list[-1]:
721
+ l, u = s.search(n)
722
+ return l == u
723
+ from sympy.ntheory.factor_ import factor_cache
724
+ if (ret := factor_cache.get(n)) is not None:
725
+ return ret == n
726
+
727
+ # If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
728
+ # This should be a bit faster than our step 2, and for large values will
729
+ # be a lot faster than our step 3 (C+GMP vs. Python).
730
+ if _gmpy is not None:
731
+ return is_strong_bpsw_prp(n)
732
+
733
+
734
+ # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
735
+ # https://miller-rabin.appspot.com/
736
+ # for lists. We have made sure the M-R routine will successfully handle
737
+ # bases larger than n, so we can use the minimal set.
738
+ # In September 2015 deterministic numbers were extended to over 2^81.
739
+ # https://arxiv.org/pdf/1509.00864.pdf
740
+ # https://oeis.org/A014233
741
+ if n < 341531:
742
+ return mr(n, [9345883071009581737])
743
+ if n < 4296595241:
744
+ # Michal Forisek and Jakub Jancina,
745
+ # Fast Primality Testing for Integers That Fit into a Machine Word
746
+ # https://ceur-ws.org/Vol-1326/020-Forisek.pdf
747
+ h = ((n >> 16) ^ n) * 0x45d9f3b
748
+ h = ((h >> 16) ^ h) * 0x45d9f3b
749
+ h = ((h >> 16) ^ h) & 255
750
+ return mr(n, [_MR_BASES_32[h]])
751
+ if n < 350269456337:
752
+ return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
753
+ if n < 55245642489451:
754
+ return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
755
+ if n < 7999252175582851:
756
+ return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
757
+ if n < 585226005592931977:
758
+ return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
759
+ if n < 18446744073709551616:
760
+ return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
761
+ if n < 318665857834031151167461:
762
+ return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
763
+ if n < 3317044064679887385961981:
764
+ return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
765
+
766
+ # We could do this instead at any point:
767
+ #if n < 18446744073709551616:
768
+ # return mr(n, [2]) and is_extra_strong_lucas_prp(n)
769
+
770
+ # Here are tests that are safe for MR routines that don't understand
771
+ # large bases.
772
+ #if n < 9080191:
773
+ # return mr(n, [31, 73])
774
+ #if n < 19471033:
775
+ # return mr(n, [2, 299417])
776
+ #if n < 38010307:
777
+ # return mr(n, [2, 9332593])
778
+ #if n < 316349281:
779
+ # return mr(n, [11000544, 31481107])
780
+ #if n < 4759123141:
781
+ # return mr(n, [2, 7, 61])
782
+ #if n < 105936894253:
783
+ # return mr(n, [2, 1005905886, 1340600841])
784
+ #if n < 31858317218647:
785
+ # return mr(n, [2, 642735, 553174392, 3046413974])
786
+ #if n < 3071837692357849:
787
+ # return mr(n, [2, 75088, 642735, 203659041, 3613982119])
788
+ #if n < 18446744073709551616:
789
+ # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
790
+
791
+ # Step 3: BPSW.
792
+ #
793
+ # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
794
+ # 44.0s old isprime using 46 bases
795
+ # 5.3s strong BPSW + one random base
796
+ # 4.3s extra strong BPSW + one random base
797
+ # 4.1s strong BPSW
798
+ # 3.2s extra strong BPSW
799
+
800
+ # Classic BPSW from page 1401 of the paper. See alternate ideas below.
801
+ return is_strong_bpsw_prp(n)
802
+
803
+ # Using extra strong test, which is somewhat faster
804
+ #return mr(n, [2]) and is_extra_strong_lucas_prp(n)
805
+
806
+ # Add a random M-R base
807
+ #import random
808
+ #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
809
+
810
+
811
+ def is_gaussian_prime(num):
812
+ r"""Test if num is a Gaussian prime number.
813
+
814
+ References
815
+ ==========
816
+
817
+ .. [1] https://oeis.org/wiki/Gaussian_primes
818
+ """
819
+
820
+ num = sympify(num)
821
+ a, b = num.as_real_imag()
822
+ a = as_int(a, strict=False)
823
+ b = as_int(b, strict=False)
824
+ if a == 0:
825
+ b = abs(b)
826
+ return isprime(b) and b % 4 == 3
827
+ elif b == 0:
828
+ a = abs(a)
829
+ return isprime(a) and a % 4 == 3
830
+ return isprime(a**2 + b**2)
.venv/lib/python3.12/site-packages/sympy/ntheory/qs.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import exp, log
2
+ from sympy.core.random import _randint
3
+ from sympy.external.gmpy import bit_scan1, gcd, invert, sqrt as isqrt
4
+ from sympy.ntheory.factor_ import _perfect_power
5
+ from sympy.ntheory.primetest import isprime
6
+ from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
7
+
8
+
9
+ class SievePolynomial:
10
+ def __init__(self, a, b, N):
11
+ """This class denotes the sieve polynomial.
12
+ Provide methods to compute `(a*x + b)**2 - N` and
13
+ `a*x + b` when given `x`.
14
+
15
+ Parameters
16
+ ==========
17
+
18
+ a : parameter of the sieve polynomial
19
+ b : parameter of the sieve polynomial
20
+ N : number to be factored
21
+
22
+ """
23
+ self.a = a
24
+ self.b = b
25
+ self.a2 = a**2
26
+ self.ab = 2*a*b
27
+ self.b2 = b**2 - N
28
+
29
+ def eval_u(self, x):
30
+ return self.a*x + self.b
31
+
32
+ def eval_v(self, x):
33
+ return (self.a2*x + self.ab)*x + self.b2
34
+
35
+
36
+ class FactorBaseElem:
37
+ """This class stores an element of the `factor_base`.
38
+ """
39
+ def __init__(self, prime, tmem_p, log_p):
40
+ """
41
+ Initialization of factor_base_elem.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ prime : prime number of the factor_base
47
+ tmem_p : Integer square root of x**2 = n mod prime
48
+ log_p : Compute Natural Logarithm of the prime
49
+ """
50
+ self.prime = prime
51
+ self.tmem_p = tmem_p
52
+ self.log_p = log_p
53
+ # `soln1` and `soln2` are solutions to
54
+ # the equation `(a*x + b)**2 - N = 0 (mod p)`.
55
+ self.soln1 = None
56
+ self.soln2 = None
57
+ self.b_ainv = None
58
+
59
+
60
+ def _generate_factor_base(prime_bound, n):
61
+ """Generate `factor_base` for Quadratic Sieve. The `factor_base`
62
+ consists of all the points whose ``legendre_symbol(n, p) == 1``
63
+ and ``p < num_primes``. Along with the prime `factor_base` also stores
64
+ natural logarithm of prime and the residue n modulo p.
65
+ It also returns the of primes numbers in the `factor_base` which are
66
+ close to 1000 and 5000.
67
+
68
+ Parameters
69
+ ==========
70
+
71
+ prime_bound : upper prime bound of the factor_base
72
+ n : integer to be factored
73
+ """
74
+ from sympy.ntheory.generate import sieve
75
+ factor_base = []
76
+ idx_1000, idx_5000 = None, None
77
+ for prime in sieve.primerange(1, prime_bound):
78
+ if pow(n, (prime - 1) // 2, prime) == 1:
79
+ if prime > 1000 and idx_1000 is None:
80
+ idx_1000 = len(factor_base) - 1
81
+ if prime > 5000 and idx_5000 is None:
82
+ idx_5000 = len(factor_base) - 1
83
+ residue = _sqrt_mod_prime_power(n, prime, 1)[0]
84
+ log_p = round(log(prime)*2**10)
85
+ factor_base.append(FactorBaseElem(prime, residue, log_p))
86
+ return idx_1000, idx_5000, factor_base
87
+
88
+
89
+ def _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
90
+ """ Generate sieve polynomials indefinitely.
91
+ Information such as `soln1` in the `factor_base` associated with
92
+ the polynomial is modified in place.
93
+
94
+ Parameters
95
+ ==========
96
+
97
+ N : Number to be factored
98
+ M : sieve interval
99
+ factor_base : factor_base primes
100
+ idx_1000 : index of prime number in the factor_base near 1000
101
+ idx_5000 : index of prime number in the factor_base near to 5000
102
+ randint : A callable that takes two integers (a, b) and returns a random integer
103
+ n such that a <= n <= b, similar to `random.randint`.
104
+ """
105
+ approx_val = log(2*N)/2 - log(M)
106
+ start = idx_1000 or 0
107
+ end = idx_5000 or (len(factor_base) - 1)
108
+ while True:
109
+ # Choose `a` that is close to `sqrt(2*N) / M`
110
+ best_a, best_q, best_ratio = None, None, None
111
+ for _ in range(50):
112
+ a = 1
113
+ q = []
114
+ while log(a) < approx_val:
115
+ rand_p = 0
116
+ while(rand_p == 0 or rand_p in q):
117
+ rand_p = randint(start, end)
118
+ p = factor_base[rand_p].prime
119
+ a *= p
120
+ q.append(rand_p)
121
+ ratio = exp(log(a) - approx_val)
122
+ if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
123
+ best_q = q
124
+ best_a = a
125
+ best_ratio = ratio
126
+
127
+ # Set `b` using the Chinese remainder theorem
128
+ a = best_a
129
+ q = best_q
130
+ B = []
131
+ for val in q:
132
+ q_l = factor_base[val].prime
133
+ gamma = factor_base[val].tmem_p * invert(a // q_l, q_l) % q_l
134
+ if 2*gamma > q_l:
135
+ gamma = q_l - gamma
136
+ B.append(a//q_l*gamma)
137
+ b = sum(B)
138
+ g = SievePolynomial(a, b, N)
139
+ for fb in factor_base:
140
+ if a % fb.prime == 0:
141
+ fb.soln1 = None
142
+ continue
143
+ a_inv = invert(a, fb.prime)
144
+ fb.b_ainv = [2*b_elem*a_inv % fb.prime for b_elem in B]
145
+ fb.soln1 = (a_inv*(fb.tmem_p - b)) % fb.prime
146
+ fb.soln2 = (a_inv*(-fb.tmem_p - b)) % fb.prime
147
+ yield g
148
+
149
+ # Update `b` with Gray code
150
+ for i in range(1, 2**(len(B)-1)):
151
+ v = bit_scan1(i)
152
+ neg_pow = 2*((i >> (v + 1)) % 2) - 1
153
+ b = g.b + 2*neg_pow*B[v]
154
+ a = g.a
155
+ g = SievePolynomial(a, b, N)
156
+ for fb in factor_base:
157
+ if fb.soln1 is None:
158
+ continue
159
+ fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v]) % fb.prime
160
+ fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v]) % fb.prime
161
+ yield g
162
+
163
+
164
+ def _gen_sieve_array(M, factor_base):
165
+ """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
166
+ that does not divide the coefficient `a` we add log_p over the sieve_array
167
+ such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
168
+ is an integer. When p = 2 then log_p is only added using
169
+ ``-M <= soln1 + i*p <= M``.
170
+
171
+ Parameters
172
+ ==========
173
+
174
+ M : sieve interval
175
+ factor_base : factor_base primes
176
+ """
177
+ sieve_array = [0]*(2*M + 1)
178
+ for factor in factor_base:
179
+ if factor.soln1 is None: #The prime does not divides a
180
+ continue
181
+ for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
182
+ sieve_array[idx] += factor.log_p
183
+ if factor.prime == 2:
184
+ continue
185
+ #if prime is 2 then sieve only with soln_1_p
186
+ for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
187
+ sieve_array[idx] += factor.log_p
188
+ return sieve_array
189
+
190
+
191
+ def _check_smoothness(num, factor_base):
192
+ r""" Check if `num` is smooth with respect to the given `factor_base`
193
+ and compute its factorization vector.
194
+
195
+ Parameters
196
+ ==========
197
+
198
+ num : integer whose smootheness is to be checked
199
+ factor_base : factor_base primes
200
+ """
201
+ if num < 0:
202
+ num *= -1
203
+ vec = 1
204
+ else:
205
+ vec = 0
206
+ for i, fb in enumerate(factor_base, 1):
207
+ if num % fb.prime:
208
+ continue
209
+ e = 1
210
+ num //= fb.prime
211
+ while num % fb.prime == 0:
212
+ e += 1
213
+ num //= fb.prime
214
+ if e % 2:
215
+ vec += 1 << i
216
+ return vec, num
217
+
218
+
219
+ def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
220
+ """Trial division stage. Here we trial divide the values generetated
221
+ by sieve_poly in the sieve interval and if it is a smooth number then
222
+ it is stored in `smooth_relations`. Moreover, if we find two partial relations
223
+ with same large prime then they are combined to form a smooth relation.
224
+ First we iterate over sieve array and look for values which are greater
225
+ than accumulated_val, as these values have a high chance of being smooth
226
+ number. Then using these values we find smooth relations.
227
+ In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
228
+ with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
229
+ to form a smooth relation.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ N : Number to be factored
235
+ M : sieve interval
236
+ factor_base : factor_base primes
237
+ sieve_array : stores log_p values
238
+ sieve_poly : polynomial from which we find smooth relations
239
+ partial_relations : stores partial relations with one large prime
240
+ ERROR_TERM : error term for accumulated_val
241
+ """
242
+ accumulated_val = (log(M) + log(N)/2 - ERROR_TERM) * 2**10
243
+ smooth_relations = []
244
+ proper_factor = set()
245
+ partial_relation_upper_bound = 128*factor_base[-1].prime
246
+ for x, val in enumerate(sieve_array, -M):
247
+ if val < accumulated_val:
248
+ continue
249
+ v = sieve_poly.eval_v(x)
250
+ vec, num = _check_smoothness(v, factor_base)
251
+ if num == 1:
252
+ smooth_relations.append((sieve_poly.eval_u(x), v, vec))
253
+ elif num < partial_relation_upper_bound and isprime(num):
254
+ if N % num == 0:
255
+ proper_factor.add(num)
256
+ continue
257
+ u = sieve_poly.eval_u(x)
258
+ if num in partial_relations:
259
+ u_prev, v_prev, vec_prev = partial_relations.pop(num)
260
+ u = u*u_prev*invert(num, N) % N
261
+ v = v*v_prev // num**2
262
+ vec ^= vec_prev
263
+ smooth_relations.append((u, v, vec))
264
+ else:
265
+ partial_relations[num] = (u, v, vec)
266
+ return smooth_relations, proper_factor
267
+
268
+
269
+ def _find_factor(N, smooth_relations, col):
270
+ """ Finds proper factor of N using fast gaussian reduction for modulo 2 matrix.
271
+
272
+ Parameters
273
+ ==========
274
+
275
+ N : Number to be factored
276
+ smooth_relations : Smooth relations vectors matrix
277
+ col : Number of columns in the matrix
278
+
279
+ Reference
280
+ ==========
281
+
282
+ .. [1] A fast algorithm for gaussian elimination over GF(2) and
283
+ its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige
284
+ """
285
+ matrix = [s_relation[2] for s_relation in smooth_relations]
286
+ row = len(matrix)
287
+ mark = [False] * row
288
+ for pos in range(col):
289
+ m = 1 << pos
290
+ for i in range(row):
291
+ if p := matrix[i] & m:
292
+ add_col = p ^ matrix[i]
293
+ matrix[i] = m
294
+ mark[i] = True
295
+ for j in range(i + 1, row):
296
+ if matrix[j] & m:
297
+ matrix[j] ^= add_col
298
+ break
299
+
300
+ for m, mat, rel in zip(mark, matrix, smooth_relations):
301
+ if m:
302
+ continue
303
+ u, v = rel[0], rel[1]
304
+ for m1, mat1, rel1 in zip(mark, matrix, smooth_relations):
305
+ if m1 and mat & mat1:
306
+ u *= rel1[0]
307
+ v *= rel1[1]
308
+ # assert is_square(v)
309
+ v = isqrt(v)
310
+ if 1 < (g := gcd(u - v, N)) < N:
311
+ yield g
312
+
313
+
314
+ def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
315
+ """Performs factorization using Self-Initializing Quadratic Sieve.
316
+ In SIQS, let N be a number to be factored, and this N should not be a
317
+ perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
318
+ ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
319
+ In order to find these integers X and Y we try to find relations of form
320
+ t**2 = u modN where u is a product of small primes. If we have enough of
321
+ these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
322
+ the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
323
+
324
+ Here, several optimizations are done like using multiple polynomials for
325
+ sieving, fast changing between polynomials and using partial relations.
326
+ The use of partial relations can speeds up the factoring by 2 times.
327
+
328
+ Parameters
329
+ ==========
330
+
331
+ N : Number to be Factored
332
+ prime_bound : upper bound for primes in the factor base
333
+ M : Sieve Interval
334
+ ERROR_TERM : Error term for checking smoothness
335
+ seed : seed of random number generator
336
+
337
+ Returns
338
+ =======
339
+
340
+ set(int) : A set of factors of N without considering multiplicity.
341
+ Returns ``{N}`` if factorization fails.
342
+
343
+ Examples
344
+ ========
345
+
346
+ >>> from sympy.ntheory import qs
347
+ >>> qs(25645121643901801, 2000, 10000)
348
+ {5394769, 4753701529}
349
+ >>> qs(9804659461513846513, 2000, 10000)
350
+ {4641991, 2112166839943}
351
+
352
+ See Also
353
+ ========
354
+
355
+ qs_factor
356
+
357
+ References
358
+ ==========
359
+
360
+ .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
361
+ .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
362
+ """
363
+ return set(qs_factor(N, prime_bound, M, ERROR_TERM, seed))
364
+
365
+
366
+ def qs_factor(N, prime_bound, M, ERROR_TERM=25, seed=1234):
367
+ """ Performs factorization using Self-Initializing Quadratic Sieve.
368
+
369
+ Parameters
370
+ ==========
371
+
372
+ N : Number to be Factored
373
+ prime_bound : upper bound for primes in the factor base
374
+ M : Sieve Interval
375
+ ERROR_TERM : Error term for checking smoothness
376
+ seed : seed of random number generator
377
+
378
+ Returns
379
+ =======
380
+
381
+ dict[int, int] : Factors of N.
382
+ Returns ``{N: 1}`` if factorization fails.
383
+ Note that the key is not always a prime number.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy.ntheory import qs_factor
389
+ >>> qs_factor(1009 * 100003, 2000, 10000)
390
+ {1009: 1, 100003: 1}
391
+
392
+ See Also
393
+ ========
394
+
395
+ qs
396
+
397
+ """
398
+ if N < 2:
399
+ raise ValueError("N should be greater than 1")
400
+ factors = {}
401
+ smooth_relations = []
402
+ partial_relations = {}
403
+ # Eliminate the possibility of even numbers,
404
+ # prime numbers, and perfect powers.
405
+ if N % 2 == 0:
406
+ e = 1
407
+ N //= 2
408
+ while N % 2 == 0:
409
+ N //= 2
410
+ e += 1
411
+ factors[2] = e
412
+ if isprime(N):
413
+ factors[N] = 1
414
+ return factors
415
+ if result := _perfect_power(N, 3):
416
+ n, e = result
417
+ factors[n] = e
418
+ return factors
419
+ N_copy = N
420
+ randint = _randint(seed)
421
+ idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
422
+ threshold = len(factor_base) * 105//100
423
+ for g in _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
424
+ sieve_array = _gen_sieve_array(M, factor_base)
425
+ s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, g, partial_relations, ERROR_TERM)
426
+ smooth_relations += s_rel
427
+ for p in p_f:
428
+ if N_copy % p:
429
+ continue
430
+ e = 1
431
+ N_copy //= p
432
+ while N_copy % p == 0:
433
+ N_copy //= p
434
+ e += 1
435
+ factors[p] = e
436
+ if threshold <= len(smooth_relations):
437
+ break
438
+
439
+ for factor in _find_factor(N, smooth_relations, len(factor_base) + 1):
440
+ if N_copy % factor == 0:
441
+ e = 1
442
+ N_copy //= factor
443
+ while N_copy % factor == 0:
444
+ N_copy //= factor
445
+ e += 1
446
+ factors[factor] = e
447
+ if N_copy == 1 or isprime(N_copy):
448
+ break
449
+ if N_copy != 1:
450
+ factors[N_copy] = 1
451
+ return factors
.venv/lib/python3.12/site-packages/sympy/ntheory/residue_ntheory.py ADDED
@@ -0,0 +1,1963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.external.gmpy import (gcd, lcm, invert, sqrt, jacobi,
4
+ bit_scan1, remove)
5
+ from sympy.polys import Poly
6
+ from sympy.polys.domains import ZZ
7
+ from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence, gf_csolve
8
+ from .primetest import isprime
9
+ from .generate import primerange
10
+ from .factor_ import factorint, _perfect_power
11
+ from .modular import crt
12
+ from sympy.utilities.decorator import deprecated
13
+ from sympy.utilities.memoization import recurrence_memo
14
+ from sympy.utilities.misc import as_int
15
+ from sympy.utilities.iterables import iproduct
16
+ from sympy.core.random import _randint, randint
17
+
18
+ from itertools import product
19
+
20
+
21
+ def n_order(a, n):
22
+ r""" Returns the order of ``a`` modulo ``n``.
23
+
24
+ Explanation
25
+ ===========
26
+
27
+ The order of ``a`` modulo ``n`` is the smallest integer
28
+ ``k`` such that `a^k` leaves a remainder of 1 with ``n``.
29
+
30
+ Parameters
31
+ ==========
32
+
33
+ a : integer
34
+ n : integer, n > 1. a and n should be relatively prime
35
+
36
+ Returns
37
+ =======
38
+
39
+ int : the order of ``a`` modulo ``n``
40
+
41
+ Raises
42
+ ======
43
+
44
+ ValueError
45
+ If `n \le 1` or `\gcd(a, n) \neq 1`.
46
+ If ``a`` or ``n`` is not an integer.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.ntheory import n_order
52
+ >>> n_order(3, 7)
53
+ 6
54
+ >>> n_order(4, 7)
55
+ 3
56
+
57
+ See Also
58
+ ========
59
+
60
+ is_primitive_root
61
+ We say that ``a`` is a primitive root of ``n``
62
+ when the order of ``a`` modulo ``n`` equals ``totient(n)``
63
+
64
+ """
65
+ a, n = as_int(a), as_int(n)
66
+ if n <= 1:
67
+ raise ValueError("n should be an integer greater than 1")
68
+ a = a % n
69
+ # Trivial
70
+ if a == 1:
71
+ return 1
72
+ if gcd(a, n) != 1:
73
+ raise ValueError("The two numbers should be relatively prime")
74
+ a_order = 1
75
+ for p, e in factorint(n).items():
76
+ pe = p**e
77
+ pe_order = (p - 1) * p**(e - 1)
78
+ factors = factorint(p - 1)
79
+ if e > 1:
80
+ factors[p] = e - 1
81
+ order = 1
82
+ for px, ex in factors.items():
83
+ x = pow(a, pe_order // px**ex, pe)
84
+ while x != 1:
85
+ x = pow(x, px, pe)
86
+ order *= px
87
+ a_order = lcm(a_order, order)
88
+ return int(a_order)
89
+
90
+
91
+ def _primitive_root_prime_iter(p):
92
+ r""" Generates the primitive roots for a prime ``p``.
93
+
94
+ Explanation
95
+ ===========
96
+
97
+ The primitive roots generated are not necessarily sorted.
98
+ However, the first one is the smallest primitive root.
99
+
100
+ Find the element whose order is ``p-1`` from the smaller one.
101
+ If we can find the first primitive root ``g``, we can use the following theorem.
102
+
103
+ .. math ::
104
+ \operatorname{ord}(g^k) = \frac{\operatorname{ord}(g)}{\gcd(\operatorname{ord}(g), k)}
105
+
106
+ From the assumption that `\operatorname{ord}(g)=p-1`,
107
+ it is a necessary and sufficient condition for
108
+ `\operatorname{ord}(g^k)=p-1` that `\gcd(p-1, k)=1`.
109
+
110
+ Parameters
111
+ ==========
112
+
113
+ p : odd prime
114
+
115
+ Yields
116
+ ======
117
+
118
+ int
119
+ the primitive roots of ``p``
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
125
+ >>> sorted(_primitive_root_prime_iter(19))
126
+ [2, 3, 10, 13, 14, 15]
127
+
128
+ References
129
+ ==========
130
+
131
+ .. [1] W. Stein "Elementary Number Theory" (2011), page 44
132
+
133
+ """
134
+ if p == 3:
135
+ yield 2
136
+ return
137
+ # Let p = +-1 (mod 4a). Legendre symbol (a/p) = 1, so `a` is not the primitive root.
138
+ # Corollary : If p = +-1 (mod 8), then 2 is not the primitive root of p.
139
+ g_min = 3 if p % 8 in [1, 7] else 2
140
+ if p < 41:
141
+ # small case
142
+ g = 5 if p == 23 else g_min
143
+ else:
144
+ v = [(p - 1) // i for i in factorint(p - 1).keys()]
145
+ for g in range(g_min, p):
146
+ if all(pow(g, pw, p) != 1 for pw in v):
147
+ break
148
+ yield g
149
+ # g**k is the primitive root of p iff gcd(p - 1, k) = 1
150
+ for k in range(3, p, 2):
151
+ if gcd(p - 1, k) == 1:
152
+ yield pow(g, k, p)
153
+
154
+
155
+ def _primitive_root_prime_power_iter(p, e):
156
+ r""" Generates the primitive roots of `p^e`.
157
+
158
+ Explanation
159
+ ===========
160
+
161
+ Let ``g`` be the primitive root of ``p``.
162
+ If `g^{p-1} \not\equiv 1 \pmod{p^2}`, then ``g`` is primitive root of `p^e`.
163
+ Thus, if we find a primitive root ``g`` of ``p``,
164
+ then `g, g+p, g+2p, \ldots, g+(p-1)p` are primitive roots of `p^2` except one.
165
+ That one satisfies `\hat{g}^{p-1} \equiv 1 \pmod{p^2}`.
166
+ If ``h`` is the primitive root of `p^2`,
167
+ then `h, h+p^2, h+2p^2, \ldots, h+(p^{e-2}-1)p^e` are primitive roots of `p^e`.
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ p : odd prime
173
+ e : positive integer
174
+
175
+ Yields
176
+ ======
177
+
178
+ int
179
+ the primitive roots of `p^e`
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power_iter
185
+ >>> sorted(_primitive_root_prime_power_iter(5, 2))
186
+ [2, 3, 8, 12, 13, 17, 22, 23]
187
+
188
+ """
189
+ if e == 1:
190
+ yield from _primitive_root_prime_iter(p)
191
+ else:
192
+ p2 = p**2
193
+ for g in _primitive_root_prime_iter(p):
194
+ t = (g - pow(g, 2 - p, p2)) % p2
195
+ for k in range(0, p2, p):
196
+ if k != t:
197
+ yield from (g + k + m for m in range(0, p**e, p2))
198
+
199
+
200
+ def _primitive_root_prime_power2_iter(p, e):
201
+ r""" Generates the primitive roots of `2p^e`.
202
+
203
+ Explanation
204
+ ===========
205
+
206
+ If ``g`` is the primitive root of ``p**e``,
207
+ then the odd one of ``g`` and ``g+p**e`` is the primitive root of ``2*p**e``.
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ p : odd prime
213
+ e : positive integer
214
+
215
+ Yields
216
+ ======
217
+
218
+ int
219
+ the primitive roots of `2p^e`
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power2_iter
225
+ >>> sorted(_primitive_root_prime_power2_iter(5, 2))
226
+ [3, 13, 17, 23, 27, 33, 37, 47]
227
+
228
+ """
229
+ for g in _primitive_root_prime_power_iter(p, e):
230
+ if g % 2 == 1:
231
+ yield g
232
+ else:
233
+ yield g + p**e
234
+
235
+
236
+ def primitive_root(p, smallest=True):
237
+ r""" Returns a primitive root of ``p`` or None.
238
+
239
+ Explanation
240
+ ===========
241
+
242
+ For the definition of primitive root,
243
+ see the explanation of ``is_primitive_root``.
244
+
245
+ The primitive root of ``p`` exist only for
246
+ `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
247
+ Now, if we know the primitive root of ``q``,
248
+ we can calculate the primitive root of `q^e`,
249
+ and if we know the primitive root of `q^e`,
250
+ we can calculate the primitive root of `2q^e`.
251
+ When there is no need to find the smallest primitive root,
252
+ this property can be used to obtain a fast primitive root.
253
+ On the other hand, when we want the smallest primitive root,
254
+ we naively determine whether it is a primitive root or not.
255
+
256
+ Parameters
257
+ ==========
258
+
259
+ p : integer, p > 1
260
+ smallest : if True the smallest primitive root is returned or None
261
+
262
+ Returns
263
+ =======
264
+
265
+ int | None :
266
+ If the primitive root exists, return the primitive root of ``p``.
267
+ If not, return None.
268
+
269
+ Raises
270
+ ======
271
+
272
+ ValueError
273
+ If `p \le 1` or ``p`` is not an integer.
274
+
275
+ Examples
276
+ ========
277
+
278
+ >>> from sympy.ntheory.residue_ntheory import primitive_root
279
+ >>> primitive_root(19)
280
+ 2
281
+ >>> primitive_root(21) is None
282
+ True
283
+ >>> primitive_root(50, smallest=False)
284
+ 27
285
+
286
+ See Also
287
+ ========
288
+
289
+ is_primitive_root
290
+
291
+ References
292
+ ==========
293
+
294
+ .. [1] W. Stein "Elementary Number Theory" (2011), page 44
295
+ .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
296
+
297
+ """
298
+ p = as_int(p)
299
+ if p <= 1:
300
+ raise ValueError("p should be an integer greater than 1")
301
+ if p <= 4:
302
+ return p - 1
303
+ p_even = p % 2 == 0
304
+ if not p_even:
305
+ q = p # p is odd
306
+ elif p % 4:
307
+ q = p//2 # p had 1 factor of 2
308
+ else:
309
+ return None # p had more than one factor of 2
310
+ if isprime(q):
311
+ e = 1
312
+ else:
313
+ m = _perfect_power(q, 3)
314
+ if not m:
315
+ return None
316
+ q, e = m
317
+ if not isprime(q):
318
+ return None
319
+ if not smallest:
320
+ if p_even:
321
+ return next(_primitive_root_prime_power2_iter(q, e))
322
+ return next(_primitive_root_prime_power_iter(q, e))
323
+ if p_even:
324
+ for i in range(3, p, 2):
325
+ if i % q and is_primitive_root(i, p):
326
+ return i
327
+ g = next(_primitive_root_prime_iter(q))
328
+ if e == 1 or pow(g, q - 1, q**2) != 1:
329
+ return g
330
+ for i in range(g + 1, p):
331
+ if i % q and is_primitive_root(i, p):
332
+ return i
333
+
334
+
335
+ def is_primitive_root(a, p):
336
+ r""" Returns True if ``a`` is a primitive root of ``p``.
337
+
338
+ Explanation
339
+ ===========
340
+
341
+ ``a`` is said to be the primitive root of ``p`` if `\gcd(a, p) = 1` and
342
+ `\phi(p)` is the smallest positive number s.t.
343
+
344
+ `a^{\phi(p)} \equiv 1 \pmod{p}`.
345
+
346
+ where `\phi(p)` is Euler's totient function.
347
+
348
+ The primitive root of ``p`` exist only for
349
+ `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
350
+ Hence, if it is not such a ``p``, it returns False.
351
+ To determine the primitive root, we need to know
352
+ the prime factorization of ``q-1``.
353
+ The hardness of the determination depends on this complexity.
354
+
355
+ Parameters
356
+ ==========
357
+
358
+ a : integer
359
+ p : integer, ``p`` > 1. ``a`` and ``p`` should be relatively prime
360
+
361
+ Returns
362
+ =======
363
+
364
+ bool : If True, ``a`` is the primitive root of ``p``.
365
+
366
+ Raises
367
+ ======
368
+
369
+ ValueError
370
+ If `p \le 1` or `\gcd(a, p) \neq 1`.
371
+ If ``a`` or ``p`` is not an integer.
372
+
373
+ Examples
374
+ ========
375
+
376
+ >>> from sympy.functions.combinatorial.numbers import totient
377
+ >>> from sympy.ntheory import is_primitive_root, n_order
378
+ >>> is_primitive_root(3, 10)
379
+ True
380
+ >>> is_primitive_root(9, 10)
381
+ False
382
+ >>> n_order(3, 10) == totient(10)
383
+ True
384
+ >>> n_order(9, 10) == totient(10)
385
+ False
386
+
387
+ See Also
388
+ ========
389
+
390
+ primitive_root
391
+
392
+ """
393
+ a, p = as_int(a), as_int(p)
394
+ if p <= 1:
395
+ raise ValueError("p should be an integer greater than 1")
396
+ a = a % p
397
+ if gcd(a, p) != 1:
398
+ raise ValueError("The two numbers should be relatively prime")
399
+ # Primitive root of p exist only for
400
+ # p = 2, 4, q**e, 2*q**e (q is odd prime)
401
+ if p <= 4:
402
+ # The primitive root is only p-1.
403
+ return a == p - 1
404
+ if p % 2:
405
+ q = p # p is odd
406
+ elif p % 4:
407
+ q = p//2 # p had 1 factor of 2
408
+ else:
409
+ return False # p had more than one factor of 2
410
+ if isprime(q):
411
+ group_order = q - 1
412
+ factors = factorint(q - 1).keys()
413
+ else:
414
+ m = _perfect_power(q, 3)
415
+ if not m:
416
+ return False
417
+ q, e = m
418
+ if not isprime(q):
419
+ return False
420
+ group_order = q**(e - 1)*(q - 1)
421
+ factors = set(factorint(q - 1).keys())
422
+ factors.add(q)
423
+ return all(pow(a, group_order // prime, p) != 1 for prime in factors)
424
+
425
+
426
+ def _sqrt_mod_tonelli_shanks(a, p):
427
+ """
428
+ Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
429
+
430
+ Assume that the root exists.
431
+
432
+ Parameters
433
+ ==========
434
+
435
+ a : int
436
+ p : int
437
+ prime number. should be ``p % 8 == 1``
438
+
439
+ Returns
440
+ =======
441
+
442
+ int : Generally, there are two roots, but only one is returned.
443
+ Which one is returned is random.
444
+
445
+ Examples
446
+ ========
447
+
448
+ >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_tonelli_shanks
449
+ >>> _sqrt_mod_tonelli_shanks(2, 17) in [6, 11]
450
+ True
451
+
452
+ References
453
+ ==========
454
+
455
+ .. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
456
+ 2nd Edition (2005), page 101, ISBN:978-0387252827
457
+
458
+ """
459
+ s = bit_scan1(p - 1)
460
+ t = p >> s
461
+ # find a non-quadratic residue
462
+ if p % 12 == 5:
463
+ # Legendre symbol (3/p) == -1 if p % 12 in [5, 7]
464
+ d = 3
465
+ elif p % 5 in [2, 3]:
466
+ # Legendre symbol (5/p) == -1 if p % 5 in [2, 3]
467
+ d = 5
468
+ else:
469
+ while 1:
470
+ d = randint(6, p - 1)
471
+ if jacobi(d, p) == -1:
472
+ break
473
+ #assert legendre_symbol(d, p) == -1
474
+ A = pow(a, t, p)
475
+ D = pow(d, t, p)
476
+ m = 0
477
+ for i in range(s):
478
+ adm = A*pow(D, m, p) % p
479
+ adm = pow(adm, 2**(s - 1 - i), p)
480
+ if adm % p == p - 1:
481
+ m += 2**i
482
+ #assert A*pow(D, m, p) % p == 1
483
+ x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
484
+ return x
485
+
486
+
487
+ def sqrt_mod(a, p, all_roots=False):
488
+ """
489
+ Find a root of ``x**2 = a mod p``.
490
+
491
+ Parameters
492
+ ==========
493
+
494
+ a : integer
495
+ p : positive integer
496
+ all_roots : if True the list of roots is returned or None
497
+
498
+ Notes
499
+ =====
500
+
501
+ If there is no root it is returned None; else the returned root
502
+ is less or equal to ``p // 2``; in general is not the smallest one.
503
+ It is returned ``p // 2`` only if it is the only root.
504
+
505
+ Use ``all_roots`` only when it is expected that all the roots fit
506
+ in memory; otherwise use ``sqrt_mod_iter``.
507
+
508
+ Examples
509
+ ========
510
+
511
+ >>> from sympy.ntheory import sqrt_mod
512
+ >>> sqrt_mod(11, 43)
513
+ 21
514
+ >>> sqrt_mod(17, 32, True)
515
+ [7, 9, 23, 25]
516
+ """
517
+ if all_roots:
518
+ return sorted(sqrt_mod_iter(a, p))
519
+ p = abs(as_int(p))
520
+ halfp = p // 2
521
+ x = None
522
+ for r in sqrt_mod_iter(a, p):
523
+ if r < halfp:
524
+ return r
525
+ elif r > halfp:
526
+ return p - r
527
+ else:
528
+ x = r
529
+ return x
530
+
531
+
532
+ def sqrt_mod_iter(a, p, domain=int):
533
+ """
534
+ Iterate over solutions to ``x**2 = a mod p``.
535
+
536
+ Parameters
537
+ ==========
538
+
539
+ a : integer
540
+ p : positive integer
541
+ domain : integer domain, ``int``, ``ZZ`` or ``Integer``
542
+
543
+ Examples
544
+ ========
545
+
546
+ >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
547
+ >>> list(sqrt_mod_iter(11, 43))
548
+ [21, 22]
549
+
550
+ See Also
551
+ ========
552
+
553
+ sqrt_mod : Same functionality, but you want a sorted list or only one solution.
554
+
555
+ """
556
+ a, p = as_int(a), abs(as_int(p))
557
+ v = []
558
+ pv = []
559
+ _product = product
560
+ for px, ex in factorint(p).items():
561
+ if a % px:
562
+ # `len(rx)` is at most 4
563
+ rx = _sqrt_mod_prime_power(a, px, ex)
564
+ else:
565
+ # `len(list(rx))` can be assumed to be large.
566
+ # The `itertools.product` is disadvantageous in terms of memory usage.
567
+ # It is also inferior to iproduct in speed if not all Cartesian products are needed.
568
+ rx = _sqrt_mod1(a, px, ex)
569
+ _product = iproduct
570
+ if not rx:
571
+ return
572
+ v.append(rx)
573
+ pv.append(px**ex)
574
+ if len(v) == 1:
575
+ yield from map(domain, v[0])
576
+ else:
577
+ mm, e, s = gf_crt1(pv, ZZ)
578
+ for vx in _product(*v):
579
+ yield domain(gf_crt2(vx, pv, mm, e, s, ZZ))
580
+
581
+
582
+ def _sqrt_mod_prime_power(a, p, k):
583
+ """
584
+ Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``.
585
+ If no solution exists, return ``None``.
586
+ Solutions are returned in an ascending list.
587
+
588
+ Parameters
589
+ ==========
590
+
591
+ a : integer
592
+ p : prime number
593
+ k : positive integer
594
+
595
+ Examples
596
+ ========
597
+
598
+ >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
599
+ >>> _sqrt_mod_prime_power(11, 43, 1)
600
+ [21, 22]
601
+
602
+ References
603
+ ==========
604
+
605
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 160
606
+ .. [2] http://www.numbertheory.org/php/squareroot.html
607
+ .. [3] [Gathen99]_
608
+ """
609
+ pk = p**k
610
+ a = a % pk
611
+
612
+ if p == 2:
613
+ # see Ref.[2]
614
+ if a % 8 != 1:
615
+ return None
616
+ # Trivial
617
+ if k <= 3:
618
+ return list(range(1, pk, 2))
619
+ r = 1
620
+ # r is one of the solutions to x**2 - a = 0 (mod 2**3).
621
+ # Hensel lift them to solutions of x**2 - a = 0 (mod 2**k)
622
+ # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
623
+ # then r + 2**(nx - 1) is a root mod 2**(nx+1)
624
+ for nx in range(3, k):
625
+ if ((r**2 - a) >> nx) % 2:
626
+ r += 1 << (nx - 1)
627
+ # r is a solution of x**2 - a = 0 (mod 2**k), and
628
+ # there exist other solutions -r, r+h, -(r+h), and these are all solutions.
629
+ h = 1 << (k - 1)
630
+ return sorted([r, pk - r, (r + h) % pk, -(r + h) % pk])
631
+
632
+ # If the Legendre symbol (a/p) is not 1, no solution exists.
633
+ if jacobi(a, p) != 1:
634
+ return None
635
+ if p % 4 == 3:
636
+ res = pow(a, (p + 1) // 4, p)
637
+ elif p % 8 == 5:
638
+ res = pow(a, (p + 3) // 8, p)
639
+ if pow(res, 2, p) != a % p:
640
+ res = res * pow(2, (p - 1) // 4, p) % p
641
+ else:
642
+ res = _sqrt_mod_tonelli_shanks(a, p)
643
+ if k > 1:
644
+ # Hensel lifting with Newton iteration, see Ref.[3] chapter 9
645
+ # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
646
+ px = p
647
+ for _ in range(k.bit_length() - 1):
648
+ px = px**2
649
+ frinv = invert(2*res, px)
650
+ res = (res - (res**2 - a)*frinv) % px
651
+ if k & (k - 1): # If k is not a power of 2
652
+ frinv = invert(2*res, pk)
653
+ res = (res - (res**2 - a)*frinv) % pk
654
+ return sorted([res, pk - res])
655
+
656
+
657
+ def _sqrt_mod1(a, p, n):
658
+ """
659
+ Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``.
660
+ If no solution exists, return ``None``.
661
+
662
+ Parameters
663
+ ==========
664
+
665
+ a : integer
666
+ p : prime number, p must divide a
667
+ n : positive integer
668
+
669
+ References
670
+ ==========
671
+
672
+ .. [1] http://www.numbertheory.org/php/squareroot.html
673
+ """
674
+ pn = p**n
675
+ a = a % pn
676
+ if a == 0:
677
+ # case gcd(a, p**k) = p**n
678
+ return range(0, pn, p**((n + 1) // 2))
679
+ # case gcd(a, p**k) = p**r, r < n
680
+ a, r = remove(a, p)
681
+ if r % 2 == 1:
682
+ return None
683
+ res = _sqrt_mod_prime_power(a, p, n - r)
684
+ if res is None:
685
+ return None
686
+ m = r // 2
687
+ return (x for rx in res for x in range(rx*p**m, pn, p**(n - m)))
688
+
689
+
690
+ def is_quad_residue(a, p):
691
+ """
692
+ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
693
+ i.e a % p in set([i**2 % p for i in range(p)]).
694
+
695
+ Parameters
696
+ ==========
697
+
698
+ a : integer
699
+ p : positive integer
700
+
701
+ Returns
702
+ =======
703
+
704
+ bool : If True, ``x**2 == a (mod p)`` has solution.
705
+
706
+ Raises
707
+ ======
708
+
709
+ ValueError
710
+ If ``a``, ``p`` is not integer.
711
+ If ``p`` is not positive.
712
+
713
+ Examples
714
+ ========
715
+
716
+ >>> from sympy.ntheory import is_quad_residue
717
+ >>> is_quad_residue(21, 100)
718
+ True
719
+
720
+ Indeed, ``pow(39, 2, 100)`` would be 21.
721
+
722
+ >>> is_quad_residue(21, 120)
723
+ False
724
+
725
+ That is, for any integer ``x``, ``pow(x, 2, 120)`` is not 21.
726
+
727
+ If ``p`` is an odd
728
+ prime, an iterative method is used to make the determination:
729
+
730
+ >>> from sympy.ntheory import is_quad_residue
731
+ >>> sorted(set([i**2 % 7 for i in range(7)]))
732
+ [0, 1, 2, 4]
733
+ >>> [j for j in range(7) if is_quad_residue(j, 7)]
734
+ [0, 1, 2, 4]
735
+
736
+ See Also
737
+ ========
738
+
739
+ legendre_symbol, jacobi_symbol, sqrt_mod
740
+ """
741
+ a, p = as_int(a), as_int(p)
742
+ if p < 1:
743
+ raise ValueError('p must be > 0')
744
+ a %= p
745
+ if a < 2 or p < 3:
746
+ return True
747
+ # Since we want to compute the Jacobi symbol,
748
+ # we separate p into the odd part and the rest.
749
+ t = bit_scan1(p)
750
+ if t:
751
+ # The existence of a solution to a power of 2 is determined
752
+ # using the logic of `p==2` in `_sqrt_mod_prime_power` and `_sqrt_mod1`.
753
+ a_ = a % (1 << t)
754
+ if a_:
755
+ r = bit_scan1(a_)
756
+ if r % 2 or (a_ >> r) & 6:
757
+ return False
758
+ p >>= t
759
+ a %= p
760
+ if a < 2 or p < 3:
761
+ return True
762
+ # If Jacobi symbol is -1 or p is prime, can be determined by Jacobi symbol only
763
+ j = jacobi(a, p)
764
+ if j == -1 or isprime(p):
765
+ return j == 1
766
+ # Checks if `x**2 = a (mod p)` has a solution
767
+ for px, ex in factorint(p).items():
768
+ if a % px:
769
+ if jacobi(a, px) != 1:
770
+ return False
771
+ else:
772
+ a_ = a % px**ex
773
+ if a_ == 0:
774
+ continue
775
+ a_, r = remove(a_, px)
776
+ if r % 2 or jacobi(a_, px) != 1:
777
+ return False
778
+ return True
779
+
780
+
781
+ def is_nthpow_residue(a, n, m):
782
+ """
783
+ Returns True if ``x**n == a (mod m)`` has solutions.
784
+
785
+ References
786
+ ==========
787
+
788
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
789
+
790
+ """
791
+ a = a % m
792
+ a, n, m = as_int(a), as_int(n), as_int(m)
793
+ if m <= 0:
794
+ raise ValueError('m must be > 0')
795
+ if n < 0:
796
+ raise ValueError('n must be >= 0')
797
+ if n == 0:
798
+ if m == 1:
799
+ return False
800
+ return a == 1
801
+ if a == 0:
802
+ return True
803
+ if n == 1:
804
+ return True
805
+ if n == 2:
806
+ return is_quad_residue(a, m)
807
+ return all(_is_nthpow_residue_bign_prime_power(a, n, p, e)
808
+ for p, e in factorint(m).items())
809
+
810
+
811
+ def _is_nthpow_residue_bign_prime_power(a, n, p, k):
812
+ r"""
813
+ Returns True if `x^n = a \pmod{p^k}` has solutions for `n > 2`.
814
+
815
+ Parameters
816
+ ==========
817
+
818
+ a : positive integer
819
+ n : integer, n > 2
820
+ p : prime number
821
+ k : positive integer
822
+
823
+ """
824
+ while a % p == 0:
825
+ a %= pow(p, k)
826
+ if not a:
827
+ return True
828
+ a, mu = remove(a, p)
829
+ if mu % n:
830
+ return False
831
+ k -= mu
832
+ if p != 2:
833
+ f = p**(k - 1)*(p - 1) # f = totient(p**k)
834
+ return pow(a, f // gcd(f, n), pow(p, k)) == 1
835
+ if n & 1:
836
+ return True
837
+ c = min(bit_scan1(n) + 2, k)
838
+ return a % pow(2, c) == 1
839
+
840
+
841
+ def _nthroot_mod1(s, q, p, all_roots):
842
+ """
843
+ Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``.
844
+ Assume that the root exists.
845
+
846
+ Parameters
847
+ ==========
848
+
849
+ s : integer
850
+ q : integer, n > 2. ``q`` divides ``p - 1``.
851
+ p : prime number
852
+ all_roots : if False returns the smallest root, else the list of roots
853
+
854
+ Returns
855
+ =======
856
+
857
+ list[int] | int :
858
+ Root of ``x**q = s mod p``. If ``all_roots == True``,
859
+ returned ascending list. otherwise, returned an int.
860
+
861
+ Examples
862
+ ========
863
+
864
+ >>> from sympy.ntheory.residue_ntheory import _nthroot_mod1
865
+ >>> _nthroot_mod1(5, 3, 13, False)
866
+ 7
867
+ >>> _nthroot_mod1(13, 4, 17, True)
868
+ [3, 5, 12, 14]
869
+
870
+ References
871
+ ==========
872
+
873
+ .. [1] A. M. Johnston, A Generalized qth Root Algorithm,
874
+ ACM-SIAM Symposium on Discrete Algorithms (1999), pp. 929-930
875
+
876
+ """
877
+ g = next(_primitive_root_prime_iter(p))
878
+ r = s
879
+ for qx, ex in factorint(q).items():
880
+ f = (p - 1) // qx**ex
881
+ while f % qx == 0:
882
+ f //= qx
883
+ z = f*invert(-f, qx)
884
+ x = (1 + z) // qx
885
+ t = discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
886
+ for _ in range(ex):
887
+ # assert t == discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
888
+ r = pow(r, x, p)*pow(g, -z*t % (p - 1), p) % p
889
+ t //= qx
890
+ res = [r]
891
+ h = pow(g, (p - 1) // q, p)
892
+ #assert pow(h, q, p) == 1
893
+ hx = r
894
+ for _ in range(q - 1):
895
+ hx = (hx*h) % p
896
+ res.append(hx)
897
+ if all_roots:
898
+ res.sort()
899
+ return res
900
+ return min(res)
901
+
902
+
903
+ def _nthroot_mod_prime_power(a, n, p, k):
904
+ """ Root of ``x**n = a mod p**k``.
905
+
906
+ Parameters
907
+ ==========
908
+
909
+ a : integer
910
+ n : integer, n > 2
911
+ p : prime number
912
+ k : positive integer
913
+
914
+ Returns
915
+ =======
916
+
917
+ list[int] :
918
+ Ascending list of roots of ``x**n = a mod p**k``.
919
+ If no solution exists, return ``[]``.
920
+
921
+ """
922
+ if not _is_nthpow_residue_bign_prime_power(a, n, p, k):
923
+ return []
924
+ a_mod_p = a % p
925
+ if a_mod_p == 0:
926
+ base_roots = [0]
927
+ elif (p - 1) % n == 0:
928
+ base_roots = _nthroot_mod1(a_mod_p, n, p, all_roots=True)
929
+ else:
930
+ # The roots of ``x**n - a = 0 (mod p)`` are roots of
931
+ # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
932
+ pa = n
933
+ pb = p - 1
934
+ b = 1
935
+ if pa < pb:
936
+ a_mod_p, pa, b, pb = b, pb, a_mod_p, pa
937
+ # gcd(x**pa - a, x**pb - b) = gcd(x**pb - b, x**pc - c)
938
+ # where pc = pa % pb; c = b**-q * a mod p
939
+ while pb:
940
+ q, pc = divmod(pa, pb)
941
+ c = pow(b, -q, p) * a_mod_p % p
942
+ pa, pb = pb, pc
943
+ a_mod_p, b = b, c
944
+ if pa == 1:
945
+ base_roots = [a_mod_p]
946
+ elif pa == 2:
947
+ base_roots = sqrt_mod(a_mod_p, p, all_roots=True)
948
+ else:
949
+ base_roots = _nthroot_mod1(a_mod_p, pa, p, all_roots=True)
950
+ if k == 1:
951
+ return base_roots
952
+ a %= p**k
953
+ tot_roots = set()
954
+ for root in base_roots:
955
+ diff = pow(root, n - 1, p)*n % p
956
+ new_base = p
957
+ if diff != 0:
958
+ m_inv = invert(diff, p)
959
+ for _ in range(k - 1):
960
+ new_base *= p
961
+ tmp = pow(root, n, new_base) - a
962
+ tmp *= m_inv
963
+ root = (root - tmp) % new_base
964
+ tot_roots.add(root)
965
+ else:
966
+ roots_in_base = {root}
967
+ for _ in range(k - 1):
968
+ new_base *= p
969
+ new_roots = set()
970
+ for k_ in roots_in_base:
971
+ if pow(k_, n, new_base) != a % new_base:
972
+ continue
973
+ while k_ not in new_roots:
974
+ new_roots.add(k_)
975
+ k_ = (k_ + (new_base // p)) % new_base
976
+ roots_in_base = new_roots
977
+ tot_roots = tot_roots | roots_in_base
978
+ return sorted(tot_roots)
979
+
980
+
981
+ def nthroot_mod(a, n, p, all_roots=False):
982
+ """
983
+ Find the solutions to ``x**n = a mod p``.
984
+
985
+ Parameters
986
+ ==========
987
+
988
+ a : integer
989
+ n : positive integer
990
+ p : positive integer
991
+ all_roots : if False returns the smallest root, else the list of roots
992
+
993
+ Returns
994
+ =======
995
+
996
+ list[int] | int | None :
997
+ solutions to ``x**n = a mod p``.
998
+ The table of the output type is:
999
+
1000
+ ========== ========== ==========
1001
+ all_roots has roots Returns
1002
+ ========== ========== ==========
1003
+ True Yes list[int]
1004
+ True No []
1005
+ False Yes int
1006
+ False No None
1007
+ ========== ========== ==========
1008
+
1009
+ Raises
1010
+ ======
1011
+
1012
+ ValueError
1013
+ If ``a``, ``n`` or ``p`` is not integer.
1014
+ If ``n`` or ``p`` is not positive.
1015
+
1016
+ Examples
1017
+ ========
1018
+
1019
+ >>> from sympy.ntheory.residue_ntheory import nthroot_mod
1020
+ >>> nthroot_mod(11, 4, 19)
1021
+ 8
1022
+ >>> nthroot_mod(11, 4, 19, True)
1023
+ [8, 11]
1024
+ >>> nthroot_mod(68, 3, 109)
1025
+ 23
1026
+
1027
+ References
1028
+ ==========
1029
+
1030
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
1031
+
1032
+ """
1033
+ a = a % p
1034
+ a, n, p = as_int(a), as_int(n), as_int(p)
1035
+
1036
+ if n < 1:
1037
+ raise ValueError("n should be positive")
1038
+ if p < 1:
1039
+ raise ValueError("p should be positive")
1040
+ if n == 1:
1041
+ return [a] if all_roots else a
1042
+ if n == 2:
1043
+ return sqrt_mod(a, p, all_roots)
1044
+ base = []
1045
+ prime_power = []
1046
+ for q, e in factorint(p).items():
1047
+ tot_roots = _nthroot_mod_prime_power(a, n, q, e)
1048
+ if not tot_roots:
1049
+ return [] if all_roots else None
1050
+ prime_power.append(q**e)
1051
+ base.append(sorted(tot_roots))
1052
+ P, E, S = gf_crt1(prime_power, ZZ)
1053
+ ret = sorted(map(int, {gf_crt2(c, prime_power, P, E, S, ZZ)
1054
+ for c in product(*base)}))
1055
+ if all_roots:
1056
+ return ret
1057
+ if ret:
1058
+ return ret[0]
1059
+
1060
+
1061
+ def quadratic_residues(p) -> list[int]:
1062
+ """
1063
+ Returns the list of quadratic residues.
1064
+
1065
+ Examples
1066
+ ========
1067
+
1068
+ >>> from sympy.ntheory.residue_ntheory import quadratic_residues
1069
+ >>> quadratic_residues(7)
1070
+ [0, 1, 2, 4]
1071
+ """
1072
+ p = as_int(p)
1073
+ r = {pow(i, 2, p) for i in range(p // 2 + 1)}
1074
+ return sorted(r)
1075
+
1076
+
1077
+ @deprecated("""\
1078
+ The `sympy.ntheory.residue_ntheory.legendre_symbol` has been moved to `sympy.functions.combinatorial.numbers.legendre_symbol`.""",
1079
+ deprecated_since_version="1.13",
1080
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1081
+ def legendre_symbol(a, p):
1082
+ r"""
1083
+ Returns the Legendre symbol `(a / p)`.
1084
+
1085
+ .. deprecated:: 1.13
1086
+
1087
+ The ``legendre_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.legendre_symbol`
1088
+ instead. See its documentation for more information. See
1089
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1090
+
1091
+ For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
1092
+ defined as
1093
+
1094
+ .. math ::
1095
+ \genfrac(){}{}{a}{p} = \begin{cases}
1096
+ 0 & \text{if } p \text{ divides } a\\
1097
+ 1 & \text{if } a \text{ is a quadratic residue modulo } p\\
1098
+ -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
1099
+ \end{cases}
1100
+
1101
+ Parameters
1102
+ ==========
1103
+
1104
+ a : integer
1105
+ p : odd prime
1106
+
1107
+ Examples
1108
+ ========
1109
+
1110
+ >>> from sympy.functions.combinatorial.numbers import legendre_symbol
1111
+ >>> [legendre_symbol(i, 7) for i in range(7)]
1112
+ [0, 1, 1, -1, 1, -1, -1]
1113
+ >>> sorted(set([i**2 % 7 for i in range(7)]))
1114
+ [0, 1, 2, 4]
1115
+
1116
+ See Also
1117
+ ========
1118
+
1119
+ is_quad_residue, jacobi_symbol
1120
+
1121
+ """
1122
+ from sympy.functions.combinatorial.numbers import legendre_symbol as _legendre_symbol
1123
+ return _legendre_symbol(a, p)
1124
+
1125
+
1126
+ @deprecated("""\
1127
+ The `sympy.ntheory.residue_ntheory.jacobi_symbol` has been moved to `sympy.functions.combinatorial.numbers.jacobi_symbol`.""",
1128
+ deprecated_since_version="1.13",
1129
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1130
+ def jacobi_symbol(m, n):
1131
+ r"""
1132
+ Returns the Jacobi symbol `(m / n)`.
1133
+
1134
+ .. deprecated:: 1.13
1135
+
1136
+ The ``jacobi_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.jacobi_symbol`
1137
+ instead. See its documentation for more information. See
1138
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1139
+
1140
+ For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
1141
+ is defined as the product of the Legendre symbols corresponding to the
1142
+ prime factors of ``n``:
1143
+
1144
+ .. math ::
1145
+ \genfrac(){}{}{m}{n} =
1146
+ \genfrac(){}{}{m}{p^{1}}^{\alpha_1}
1147
+ \genfrac(){}{}{m}{p^{2}}^{\alpha_2}
1148
+ ...
1149
+ \genfrac(){}{}{m}{p^{k}}^{\alpha_k}
1150
+ \text{ where } n =
1151
+ p_1^{\alpha_1}
1152
+ p_2^{\alpha_2}
1153
+ ...
1154
+ p_k^{\alpha_k}
1155
+
1156
+ Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
1157
+ then ``m`` is a quadratic nonresidue modulo ``n``.
1158
+
1159
+ But, unlike the Legendre symbol, if the Jacobi symbol
1160
+ `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
1161
+ modulo ``n``.
1162
+
1163
+ Parameters
1164
+ ==========
1165
+
1166
+ m : integer
1167
+ n : odd positive integer
1168
+
1169
+ Examples
1170
+ ========
1171
+
1172
+ >>> from sympy.functions.combinatorial.numbers import jacobi_symbol, legendre_symbol
1173
+ >>> from sympy import S
1174
+ >>> jacobi_symbol(45, 77)
1175
+ -1
1176
+ >>> jacobi_symbol(60, 121)
1177
+ 1
1178
+
1179
+ The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
1180
+ be demonstrated as follows:
1181
+
1182
+ >>> L = legendre_symbol
1183
+ >>> S(45).factors()
1184
+ {3: 2, 5: 1}
1185
+ >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
1186
+ True
1187
+
1188
+ See Also
1189
+ ========
1190
+
1191
+ is_quad_residue, legendre_symbol
1192
+ """
1193
+ from sympy.functions.combinatorial.numbers import jacobi_symbol as _jacobi_symbol
1194
+ return _jacobi_symbol(m, n)
1195
+
1196
+
1197
+ @deprecated("""\
1198
+ The `sympy.ntheory.residue_ntheory.mobius` has been moved to `sympy.functions.combinatorial.numbers.mobius`.""",
1199
+ deprecated_since_version="1.13",
1200
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1201
+ def mobius(n):
1202
+ """
1203
+ Mobius function maps natural number to {-1, 0, 1}
1204
+
1205
+ .. deprecated:: 1.13
1206
+
1207
+ The ``mobius`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.mobius`
1208
+ instead. See its documentation for more information. See
1209
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1210
+
1211
+ It is defined as follows:
1212
+ 1) `1` if `n = 1`.
1213
+ 2) `0` if `n` has a squared prime factor.
1214
+ 3) `(-1)^k` if `n` is a square-free positive integer with `k`
1215
+ number of prime factors.
1216
+
1217
+ It is an important multiplicative function in number theory
1218
+ and combinatorics. It has applications in mathematical series,
1219
+ algebraic number theory and also physics (Fermion operator has very
1220
+ concrete realization with Mobius Function model).
1221
+
1222
+ Parameters
1223
+ ==========
1224
+
1225
+ n : positive integer
1226
+
1227
+ Examples
1228
+ ========
1229
+
1230
+ >>> from sympy.functions.combinatorial.numbers import mobius
1231
+ >>> mobius(13*7)
1232
+ 1
1233
+ >>> mobius(1)
1234
+ 1
1235
+ >>> mobius(13*7*5)
1236
+ -1
1237
+ >>> mobius(13**2)
1238
+ 0
1239
+
1240
+ References
1241
+ ==========
1242
+
1243
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
1244
+ .. [2] Thomas Koshy "Elementary Number Theory with Applications"
1245
+
1246
+ """
1247
+ from sympy.functions.combinatorial.numbers import mobius as _mobius
1248
+ return _mobius(n)
1249
+
1250
+
1251
+ def _discrete_log_trial_mul(n, a, b, order=None):
1252
+ """
1253
+ Trial multiplication algorithm for computing the discrete logarithm of
1254
+ ``a`` to the base ``b`` modulo ``n``.
1255
+
1256
+ The algorithm finds the discrete logarithm using exhaustive search. This
1257
+ naive method is used as fallback algorithm of ``discrete_log`` when the
1258
+ group order is very small. The value ``n`` must be greater than 1.
1259
+
1260
+ Examples
1261
+ ========
1262
+
1263
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
1264
+ >>> _discrete_log_trial_mul(41, 15, 7)
1265
+ 3
1266
+
1267
+ See Also
1268
+ ========
1269
+
1270
+ discrete_log
1271
+
1272
+ References
1273
+ ==========
1274
+
1275
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1276
+ Vanstone, S. A. (1997).
1277
+ """
1278
+ a %= n
1279
+ b %= n
1280
+ if order is None:
1281
+ order = n
1282
+ x = 1
1283
+ for i in range(order):
1284
+ if x == a:
1285
+ return i
1286
+ x = x * b % n
1287
+ raise ValueError("Log does not exist")
1288
+
1289
+
1290
+ def _discrete_log_shanks_steps(n, a, b, order=None):
1291
+ """
1292
+ Baby-step giant-step algorithm for computing the discrete logarithm of
1293
+ ``a`` to the base ``b`` modulo ``n``.
1294
+
1295
+ The algorithm is a time-memory trade-off of the method of exhaustive
1296
+ search. It uses `O(sqrt(m))` memory, where `m` is the group order.
1297
+
1298
+ Examples
1299
+ ========
1300
+
1301
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
1302
+ >>> _discrete_log_shanks_steps(41, 15, 7)
1303
+ 3
1304
+
1305
+ See Also
1306
+ ========
1307
+
1308
+ discrete_log
1309
+
1310
+ References
1311
+ ==========
1312
+
1313
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1314
+ Vanstone, S. A. (1997).
1315
+ """
1316
+ a %= n
1317
+ b %= n
1318
+ if order is None:
1319
+ order = n_order(b, n)
1320
+ m = sqrt(order) + 1
1321
+ T = {}
1322
+ x = 1
1323
+ for i in range(m):
1324
+ T[x] = i
1325
+ x = x * b % n
1326
+ z = pow(b, -m, n)
1327
+ x = a
1328
+ for i in range(m):
1329
+ if x in T:
1330
+ return i * m + T[x]
1331
+ x = x * z % n
1332
+ raise ValueError("Log does not exist")
1333
+
1334
+
1335
+ def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
1336
+ """
1337
+ Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
1338
+ the base ``b`` modulo ``n``.
1339
+
1340
+ It is a randomized algorithm with the same expected running time as
1341
+ ``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
1342
+
1343
+ Examples
1344
+ ========
1345
+
1346
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
1347
+ >>> _discrete_log_pollard_rho(227, 3**7, 3)
1348
+ 7
1349
+
1350
+ See Also
1351
+ ========
1352
+
1353
+ discrete_log
1354
+
1355
+ References
1356
+ ==========
1357
+
1358
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1359
+ Vanstone, S. A. (1997).
1360
+ """
1361
+ a %= n
1362
+ b %= n
1363
+
1364
+ if order is None:
1365
+ order = n_order(b, n)
1366
+ randint = _randint(rseed)
1367
+
1368
+ for i in range(retries):
1369
+ aa = randint(1, order - 1)
1370
+ ba = randint(1, order - 1)
1371
+ xa = pow(b, aa, n) * pow(a, ba, n) % n
1372
+
1373
+ c = xa % 3
1374
+ if c == 0:
1375
+ xb = a * xa % n
1376
+ ab = aa
1377
+ bb = (ba + 1) % order
1378
+ elif c == 1:
1379
+ xb = xa * xa % n
1380
+ ab = (aa + aa) % order
1381
+ bb = (ba + ba) % order
1382
+ else:
1383
+ xb = b * xa % n
1384
+ ab = (aa + 1) % order
1385
+ bb = ba
1386
+
1387
+ for j in range(order):
1388
+ c = xa % 3
1389
+ if c == 0:
1390
+ xa = a * xa % n
1391
+ ba = (ba + 1) % order
1392
+ elif c == 1:
1393
+ xa = xa * xa % n
1394
+ aa = (aa + aa) % order
1395
+ ba = (ba + ba) % order
1396
+ else:
1397
+ xa = b * xa % n
1398
+ aa = (aa + 1) % order
1399
+
1400
+ c = xb % 3
1401
+ if c == 0:
1402
+ xb = a * xb % n
1403
+ bb = (bb + 1) % order
1404
+ elif c == 1:
1405
+ xb = xb * xb % n
1406
+ ab = (ab + ab) % order
1407
+ bb = (bb + bb) % order
1408
+ else:
1409
+ xb = b * xb % n
1410
+ ab = (ab + 1) % order
1411
+
1412
+ c = xb % 3
1413
+ if c == 0:
1414
+ xb = a * xb % n
1415
+ bb = (bb + 1) % order
1416
+ elif c == 1:
1417
+ xb = xb * xb % n
1418
+ ab = (ab + ab) % order
1419
+ bb = (bb + bb) % order
1420
+ else:
1421
+ xb = b * xb % n
1422
+ ab = (ab + 1) % order
1423
+
1424
+ if xa == xb:
1425
+ r = (ba - bb) % order
1426
+ try:
1427
+ e = invert(r, order) * (ab - aa) % order
1428
+ if (pow(b, e, n) - a) % n == 0:
1429
+ return e
1430
+ except ZeroDivisionError:
1431
+ pass
1432
+ break
1433
+ raise ValueError("Pollard's Rho failed to find logarithm")
1434
+
1435
+
1436
+ def _discrete_log_is_smooth(n: int, factorbase: list):
1437
+ """Try to factor n with respect to a given factorbase.
1438
+ Upon success a list of exponents with respect to the factorbase is returned.
1439
+ Otherwise None."""
1440
+ factors = [0]*len(factorbase)
1441
+ for i, p in enumerate(factorbase):
1442
+ while n % p == 0: # divide by p as many times as possible
1443
+ factors[i] += 1
1444
+ n = n // p
1445
+ if n != 1:
1446
+ return None # the number factors if at the end nothing is left
1447
+ return factors
1448
+
1449
+
1450
+ def _discrete_log_index_calculus(n, a, b, order, rseed=None):
1451
+ """
1452
+ Index Calculus algorithm for computing the discrete logarithm of ``a`` to
1453
+ the base ``b`` modulo ``n``.
1454
+
1455
+ The group order must be given and prime. It is not suitable for small orders
1456
+ and the algorithm might fail to find a solution in such situations.
1457
+
1458
+ Examples
1459
+ ========
1460
+
1461
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_index_calculus
1462
+ >>> _discrete_log_index_calculus(24570203447, 23859756228, 2, 12285101723)
1463
+ 4519867240
1464
+
1465
+ See Also
1466
+ ========
1467
+
1468
+ discrete_log
1469
+
1470
+ References
1471
+ ==========
1472
+
1473
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1474
+ Vanstone, S. A. (1997).
1475
+ """
1476
+ randint = _randint(rseed)
1477
+ from math import sqrt, exp, log
1478
+ a %= n
1479
+ b %= n
1480
+ # assert isprime(order), "The order of the base must be prime."
1481
+ # First choose a heuristic the bound B for the factorbase.
1482
+ # We have added an extra term to the asymptotic value which
1483
+ # is closer to the theoretical optimum for n up to 2^70.
1484
+ B = int(exp(0.5 * sqrt( log(n) * log(log(n)) )*( 1 + 1/log(log(n)) )))
1485
+ max = 5 * B * B # expected number of tries to find a relation
1486
+ factorbase = list(primerange(B)) # compute the factorbase
1487
+ lf = len(factorbase) # length of the factorbase
1488
+ ordermo = order-1
1489
+ abx = a
1490
+ for x in range(order):
1491
+ if abx == 1:
1492
+ return (order - x) % order
1493
+ relationa = _discrete_log_is_smooth(abx, factorbase)
1494
+ if relationa:
1495
+ relationa = [r % order for r in relationa] + [x]
1496
+ break
1497
+ abx = abx * b % n # abx = a*pow(b, x, n) % n
1498
+
1499
+ else:
1500
+ raise ValueError("Index Calculus failed")
1501
+
1502
+ relations = [None] * lf
1503
+ k = 1 # number of relations found
1504
+ kk = 0
1505
+ while k < 3 * lf and kk < max: # find relations for all primes in our factor base
1506
+ x = randint(1,ordermo)
1507
+ relation = _discrete_log_is_smooth(pow(b,x,n), factorbase)
1508
+ if relation is None:
1509
+ kk += 1
1510
+ continue
1511
+ k += 1
1512
+ kk = 0
1513
+ relation += [ x ]
1514
+ index = lf # determine the index of the first nonzero entry
1515
+ for i in range(lf):
1516
+ ri = relation[i] % order
1517
+ if ri> 0 and relations[i] is not None: # make this entry zero if we can
1518
+ for j in range(lf+1):
1519
+ relation[j] = (relation[j] - ri*relations[i][j]) % order
1520
+ else:
1521
+ relation[i] = ri
1522
+ if relation[i] > 0 and index == lf: # is this the index of the first nonzero entry?
1523
+ index = i
1524
+ if index == lf or relations[index] is not None: # the relation contains no new information
1525
+ continue
1526
+ # the relation contains new information
1527
+ rinv = pow(relation[index],-1,order) # normalize the first nonzero entry
1528
+ for j in range(index,lf+1):
1529
+ relation[j] = rinv * relation[j] % order
1530
+ relations[index] = relation
1531
+ for i in range(lf): # subtract the new relation from the one for a
1532
+ if relationa[i] > 0 and relations[i] is not None:
1533
+ rbi = relationa[i]
1534
+ for j in range(lf+1):
1535
+ relationa[j] = (relationa[j] - rbi*relations[i][j]) % order
1536
+ if relationa[i] > 0: # the index of the first nonzero entry
1537
+ break # we do not need to reduce further at this point
1538
+ else: # all unknowns are gone
1539
+ #print(f"Success after {k} relations out of {lf}")
1540
+ x = (order -relationa[lf]) % order
1541
+ if pow(b,x,n) == a:
1542
+ return x
1543
+ raise ValueError("Index Calculus failed")
1544
+ raise ValueError("Index Calculus failed")
1545
+
1546
+
1547
+ def _discrete_log_pohlig_hellman(n, a, b, order=None, order_factors=None):
1548
+ """
1549
+ Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
1550
+ the base ``b`` modulo ``n``.
1551
+
1552
+ In order to compute the discrete logarithm, the algorithm takes advantage
1553
+ of the factorization of the group order. It is more efficient when the
1554
+ group order factors into many small primes.
1555
+
1556
+ Examples
1557
+ ========
1558
+
1559
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
1560
+ >>> _discrete_log_pohlig_hellman(251, 210, 71)
1561
+ 197
1562
+
1563
+ See Also
1564
+ ========
1565
+
1566
+ discrete_log
1567
+
1568
+ References
1569
+ ==========
1570
+
1571
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1572
+ Vanstone, S. A. (1997).
1573
+ """
1574
+ from .modular import crt
1575
+ a %= n
1576
+ b %= n
1577
+
1578
+ if order is None:
1579
+ order = n_order(b, n)
1580
+ if order_factors is None:
1581
+ order_factors = factorint(order)
1582
+ l = [0] * len(order_factors)
1583
+
1584
+ for i, (pi, ri) in enumerate(order_factors.items()):
1585
+ for j in range(ri):
1586
+ aj = pow(a * pow(b, -l[i], n), order // pi**(j + 1), n)
1587
+ bj = pow(b, order // pi, n)
1588
+ cj = discrete_log(n, aj, bj, pi, True)
1589
+ l[i] += cj * pi**j
1590
+
1591
+ d, _ = crt([pi**ri for pi, ri in order_factors.items()], l)
1592
+ return d
1593
+
1594
+
1595
+ def discrete_log(n, a, b, order=None, prime_order=None):
1596
+ """
1597
+ Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
1598
+
1599
+ This is a recursive function to reduce the discrete logarithm problem in
1600
+ cyclic groups of composite order to the problem in cyclic groups of prime
1601
+ order.
1602
+
1603
+ It employs different algorithms depending on the problem (subgroup order
1604
+ size, prime order or not):
1605
+
1606
+ * Trial multiplication
1607
+ * Baby-step giant-step
1608
+ * Pollard's Rho
1609
+ * Index Calculus
1610
+ * Pohlig-Hellman
1611
+
1612
+ Examples
1613
+ ========
1614
+
1615
+ >>> from sympy.ntheory import discrete_log
1616
+ >>> discrete_log(41, 15, 7)
1617
+ 3
1618
+
1619
+ References
1620
+ ==========
1621
+
1622
+ .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
1623
+ .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1624
+ Vanstone, S. A. (1997).
1625
+
1626
+ """
1627
+ from math import sqrt, log
1628
+ n, a, b = as_int(n), as_int(a), as_int(b)
1629
+
1630
+ if n < 1:
1631
+ raise ValueError("n should be positive")
1632
+ if n == 1:
1633
+ return 0
1634
+
1635
+ if order is None:
1636
+ # Compute the order and its factoring in one pass
1637
+ # order = totient(n), factors = factorint(order)
1638
+ factors = {}
1639
+ for px, kx in factorint(n).items():
1640
+ if kx > 1:
1641
+ if px in factors:
1642
+ factors[px] += kx - 1
1643
+ else:
1644
+ factors[px] = kx - 1
1645
+ for py, ky in factorint(px - 1).items():
1646
+ if py in factors:
1647
+ factors[py] += ky
1648
+ else:
1649
+ factors[py] = ky
1650
+ order = 1
1651
+ for px, kx in factors.items():
1652
+ order *= px**kx
1653
+ # Now the `order` is the order of the group and factors = factorint(order)
1654
+ # The order of `b` divides the order of the group.
1655
+ order_factors = {}
1656
+ for p, e in factors.items():
1657
+ i = 0
1658
+ for _ in range(e):
1659
+ if pow(b, order // p, n) == 1:
1660
+ order //= p
1661
+ i += 1
1662
+ else:
1663
+ break
1664
+ if i < e:
1665
+ order_factors[p] = e - i
1666
+
1667
+ if prime_order is None:
1668
+ prime_order = isprime(order)
1669
+
1670
+ if order < 1000:
1671
+ return _discrete_log_trial_mul(n, a, b, order)
1672
+ elif prime_order:
1673
+ # Shanks and Pollard rho are O(sqrt(order)) while index calculus is O(exp(2*sqrt(log(n)log(log(n)))))
1674
+ # we compare the expected running times to determine the algorithm which is expected to be faster
1675
+ if 4*sqrt(log(n)*log(log(n))) < log(order) - 10: # the number 10 was determined experimental
1676
+ return _discrete_log_index_calculus(n, a, b, order)
1677
+ elif order < 1000000000000:
1678
+ # Shanks seems typically faster, but uses O(sqrt(order)) memory
1679
+ return _discrete_log_shanks_steps(n, a, b, order)
1680
+ return _discrete_log_pollard_rho(n, a, b, order)
1681
+
1682
+ return _discrete_log_pohlig_hellman(n, a, b, order, order_factors)
1683
+
1684
+
1685
+
1686
+ def quadratic_congruence(a, b, c, n):
1687
+ r"""
1688
+ Find the solutions to `a x^2 + b x + c \equiv 0 \pmod{n}`.
1689
+
1690
+ Parameters
1691
+ ==========
1692
+
1693
+ a : int
1694
+ b : int
1695
+ c : int
1696
+ n : int
1697
+ A positive integer.
1698
+
1699
+ Returns
1700
+ =======
1701
+
1702
+ list[int] :
1703
+ A sorted list of solutions. If no solution exists, ``[]``.
1704
+
1705
+ Examples
1706
+ ========
1707
+
1708
+ >>> from sympy.ntheory.residue_ntheory import quadratic_congruence
1709
+ >>> quadratic_congruence(2, 5, 3, 7) # 2x^2 + 5x + 3 = 0 (mod 7)
1710
+ [2, 6]
1711
+ >>> quadratic_congruence(8, 6, 4, 15) # No solution
1712
+ []
1713
+
1714
+ See Also
1715
+ ========
1716
+
1717
+ polynomial_congruence : Solve the polynomial congruence
1718
+
1719
+ """
1720
+ a = as_int(a)
1721
+ b = as_int(b)
1722
+ c = as_int(c)
1723
+ n = as_int(n)
1724
+ if n <= 1:
1725
+ raise ValueError("n should be an integer greater than 1")
1726
+ a %= n
1727
+ b %= n
1728
+ c %= n
1729
+
1730
+ if a == 0:
1731
+ return linear_congruence(b, -c, n)
1732
+ if n == 2:
1733
+ # assert a == 1
1734
+ roots = []
1735
+ if c == 0:
1736
+ roots.append(0)
1737
+ if (b + c) % 2:
1738
+ roots.append(1)
1739
+ return roots
1740
+ if gcd(2*a, n) == 1:
1741
+ inv_a = invert(a, n)
1742
+ b *= inv_a
1743
+ c *= inv_a
1744
+ if b % 2:
1745
+ b += n
1746
+ b >>= 1
1747
+ return sorted((i - b) % n for i in sqrt_mod_iter(b**2 - c, n))
1748
+ res = set()
1749
+ for i in sqrt_mod_iter(b**2 - 4*a*c, 4*a*n):
1750
+ q, rem = divmod(i - b, 2*a)
1751
+ if rem == 0:
1752
+ res.add(q % n)
1753
+
1754
+ return sorted(res)
1755
+
1756
+
1757
+ def _valid_expr(expr):
1758
+ """
1759
+ return coefficients of expr if it is a univariate polynomial
1760
+ with integer coefficients else raise a ValueError.
1761
+ """
1762
+
1763
+ if not expr.is_polynomial():
1764
+ raise ValueError("The expression should be a polynomial")
1765
+ polynomial = Poly(expr)
1766
+ if not polynomial.is_univariate:
1767
+ raise ValueError("The expression should be univariate")
1768
+ if not polynomial.domain == ZZ:
1769
+ raise ValueError("The expression should should have integer coefficients")
1770
+ return polynomial.all_coeffs()
1771
+
1772
+
1773
+ def polynomial_congruence(expr, m):
1774
+ """
1775
+ Find the solutions to a polynomial congruence equation modulo m.
1776
+
1777
+ Parameters
1778
+ ==========
1779
+
1780
+ expr : integer coefficient polynomial
1781
+ m : positive integer
1782
+
1783
+ Examples
1784
+ ========
1785
+
1786
+ >>> from sympy.ntheory import polynomial_congruence
1787
+ >>> from sympy.abc import x
1788
+ >>> expr = x**6 - 2*x**5 -35
1789
+ >>> polynomial_congruence(expr, 6125)
1790
+ [3257]
1791
+
1792
+ See Also
1793
+ ========
1794
+
1795
+ sympy.polys.galoistools.gf_csolve : low level solving routine used by this routine
1796
+
1797
+ """
1798
+ coefficients = _valid_expr(expr)
1799
+ coefficients = [num % m for num in coefficients]
1800
+ rank = len(coefficients)
1801
+ if rank == 3:
1802
+ return quadratic_congruence(*coefficients, m)
1803
+ if rank == 2:
1804
+ return quadratic_congruence(0, *coefficients, m)
1805
+ if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients):
1806
+ return nthroot_mod(-coefficients[-1], rank - 1, m, True)
1807
+ return gf_csolve(coefficients, m)
1808
+
1809
+
1810
+ def binomial_mod(n, m, k):
1811
+ """Compute ``binomial(n, m) % k``.
1812
+
1813
+ Explanation
1814
+ ===========
1815
+
1816
+ Returns ``binomial(n, m) % k`` using a generalization of Lucas'
1817
+ Theorem for prime powers given by Granville [1]_, in conjunction with
1818
+ the Chinese Remainder Theorem. The residue for each prime power
1819
+ is calculated in time O(log^2(n) + q^4*log(n)log(p) + q^4*p*log^3(p)).
1820
+
1821
+ Parameters
1822
+ ==========
1823
+
1824
+ n : an integer
1825
+ m : an integer
1826
+ k : a positive integer
1827
+
1828
+ Examples
1829
+ ========
1830
+
1831
+ >>> from sympy.ntheory.residue_ntheory import binomial_mod
1832
+ >>> binomial_mod(10, 2, 6) # binomial(10, 2) = 45
1833
+ 3
1834
+ >>> binomial_mod(17, 9, 10) # binomial(17, 9) = 24310
1835
+ 0
1836
+
1837
+ References
1838
+ ==========
1839
+
1840
+ .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
1841
+ Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
1842
+ """
1843
+ if k < 1: raise ValueError('k is required to be positive')
1844
+ # We decompose q into a product of prime powers and apply
1845
+ # the generalization of Lucas' Theorem given by Granville
1846
+ # to obtain binomial(n, k) mod p^e, and then use the Chinese
1847
+ # Remainder Theorem to obtain the result mod q
1848
+ if n < 0 or m < 0 or m > n: return 0
1849
+ factorisation = factorint(k)
1850
+ residues = [_binomial_mod_prime_power(n, m, p, e) for p, e in factorisation.items()]
1851
+ return crt([p**pw for p, pw in factorisation.items()], residues, check=False)[0]
1852
+
1853
+
1854
+ def _binomial_mod_prime_power(n, m, p, q):
1855
+ """Compute ``binomial(n, m) % p**q`` for a prime ``p``.
1856
+
1857
+ Parameters
1858
+ ==========
1859
+
1860
+ n : positive integer
1861
+ m : a nonnegative integer
1862
+ p : a prime
1863
+ q : a positive integer (the prime exponent)
1864
+
1865
+ Examples
1866
+ ========
1867
+
1868
+ >>> from sympy.ntheory.residue_ntheory import _binomial_mod_prime_power
1869
+ >>> _binomial_mod_prime_power(10, 2, 3, 2) # binomial(10, 2) = 45
1870
+ 0
1871
+ >>> _binomial_mod_prime_power(17, 9, 2, 4) # binomial(17, 9) = 24310
1872
+ 6
1873
+
1874
+ References
1875
+ ==========
1876
+
1877
+ .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
1878
+ Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
1879
+ """
1880
+ # Function/variable naming within this function follows Ref.[1]
1881
+ # n!_p will be used to denote the product of integers <= n not divisible by
1882
+ # p, with binomial(n, m)_p the same as binomial(n, m), but defined using
1883
+ # n!_p in place of n!
1884
+ modulo = pow(p, q)
1885
+
1886
+ def up_factorial(u):
1887
+ """Compute (u*p)!_p modulo p^q."""
1888
+ r = q // 2
1889
+ fac = prod = 1
1890
+ if r == 1 and p == 2 or 2*r + 1 in (p, p*p):
1891
+ if q % 2 == 1: r += 1
1892
+ modulo, div = pow(p, 2*r), pow(p, 2*r - q)
1893
+ else:
1894
+ modulo, div = pow(p, 2*r + 1), pow(p, (2*r + 1) - q)
1895
+ for j in range(1, r + 1):
1896
+ for mul in range((j - 1)*p + 1, j*p): # ignore jp itself
1897
+ fac *= mul
1898
+ fac %= modulo
1899
+ bj_ = bj(u, j, r)
1900
+ prod *= pow(fac, bj_, modulo)
1901
+ prod %= modulo
1902
+ if p == 2:
1903
+ sm = u // 2
1904
+ for j in range(1, r + 1): sm += j//2 * bj(u, j, r)
1905
+ if sm % 2 == 1: prod *= -1
1906
+ prod %= modulo//div
1907
+ return prod % modulo
1908
+
1909
+ def bj(u, j, r):
1910
+ """Compute the exponent of (j*p)!_p in the calculation of (u*p)!_p."""
1911
+ prod = u
1912
+ for i in range(1, r + 1):
1913
+ if i != j: prod *= u*u - i*i
1914
+ for i in range(1, r + 1):
1915
+ if i != j: prod //= j*j - i*i
1916
+ return prod // j
1917
+
1918
+ def up_plus_v_binom(u, v):
1919
+ """Compute binomial(u*p + v, v)_p modulo p^q."""
1920
+ prod = 1
1921
+ div = invert(factorial(v), modulo)
1922
+ for j in range(1, q):
1923
+ b = div
1924
+ for v_ in range(j*p + 1, j*p + v + 1):
1925
+ b *= v_
1926
+ b %= modulo
1927
+ aj = u
1928
+ for i in range(1, q):
1929
+ if i != j: aj *= u - i
1930
+ for i in range(1, q):
1931
+ if i != j: aj //= j - i
1932
+ aj //= j
1933
+ prod *= pow(b, aj, modulo)
1934
+ prod %= modulo
1935
+ return prod
1936
+
1937
+ @recurrence_memo([1])
1938
+ def factorial(v, prev):
1939
+ """Compute v! modulo p^q."""
1940
+ return v*prev[-1] % modulo
1941
+
1942
+ def factorial_p(n):
1943
+ """Compute n!_p modulo p^q."""
1944
+ u, v = divmod(n, p)
1945
+ return (factorial(v) * up_factorial(u) * up_plus_v_binom(u, v)) % modulo
1946
+
1947
+ prod = 1
1948
+ Nj, Mj, Rj = n, m, n - m
1949
+ # e0 will be the p-adic valuation of binomial(n, m) at p
1950
+ e0 = carry = eq_1 = j = 0
1951
+ while Nj:
1952
+ numerator = factorial_p(Nj % modulo)
1953
+ denominator = factorial_p(Mj % modulo) * factorial_p(Rj % modulo) % modulo
1954
+ Nj, (Mj, mj), (Rj, rj) = Nj//p, divmod(Mj, p), divmod(Rj, p)
1955
+ carry = (mj + rj + carry) // p
1956
+ e0 += carry
1957
+ if j >= q - 1: eq_1 += carry
1958
+ prod *= numerator * invert(denominator, modulo)
1959
+ prod %= modulo
1960
+ j += 1
1961
+
1962
+ mul = pow(1 if p == 2 and q >= 3 else -1, eq_1, modulo)
1963
+ return (pow(p, e0, modulo) * mul * prod) % modulo
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__init__.py ADDED
File without changes
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (194 Bytes). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-312.pyc ADDED
Binary file (10.3 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-312.pyc ADDED
Binary file (8.48 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-312.pyc ADDED
Binary file (4.25 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-312.pyc ADDED
Binary file (3.82 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-312.pyc ADDED
Binary file (3.84 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-312.pyc ADDED
Binary file (1.25 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-312.pyc ADDED
Binary file (47.2 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-312.pyc ADDED
Binary file (20.3 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_hypothesis.cpython-312.pyc ADDED
Binary file (1.77 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-312.pyc ADDED
Binary file (2.84 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-312.pyc ADDED
Binary file (3.65 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-312.pyc ADDED
Binary file (2.01 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-312.pyc ADDED
Binary file (6.44 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-312.pyc ADDED
Binary file (25.5 kB). View file
 
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_bbp_pi.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.random import randint
2
+
3
+ from sympy.ntheory.bbp_pi import pi_hex_digits
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ # http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
8
+ # There are actually 8336 listed there; with the prepended 3 there are 8337
9
+ # below
10
+ dig=''.join('''
11
+ 3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
12
+ 77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
13
+ ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
14
+ 16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
15
+ b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
16
+ 3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
17
+ b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
18
+ 1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
19
+ 91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
20
+ 392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
21
+ 68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
22
+ 888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
23
+ 061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
24
+ f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
25
+ b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
26
+ b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
27
+ cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
28
+ 829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
29
+ c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
30
+ 90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
31
+ 98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
32
+ 1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
33
+ e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
34
+ 77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
35
+ 5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
36
+ c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
37
+ e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
38
+ 6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
39
+ 7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
40
+ 3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
41
+ 266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
42
+ 373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
43
+ b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
44
+ a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
45
+ 086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
46
+ 2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
47
+ fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
48
+ dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
49
+ fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
50
+ 0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
51
+ 3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
52
+ 28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
53
+ 70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
54
+ 14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
55
+ b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
56
+ 810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
57
+ 548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
58
+ e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
59
+ c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
60
+ 85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
61
+ 41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
62
+ 35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
63
+ cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
64
+ f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
65
+ 6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
66
+ 45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
67
+ f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
68
+ b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
69
+ 5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
70
+ 2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
71
+ f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
72
+ dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
73
+ 60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
74
+ 2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
75
+ fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
76
+ 0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
77
+ 9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
78
+ 2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
79
+ fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
80
+ fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
81
+ 71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
82
+ c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
83
+ 708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
84
+ 33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
85
+ fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
86
+ b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
87
+ deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
88
+ fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
89
+ c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
90
+ 1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
91
+ 45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
92
+ c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
93
+ f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
94
+ e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
95
+ 972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
96
+ 4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
97
+ 55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
98
+ 2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
99
+ f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
100
+ 32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
101
+ dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
102
+ d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
103
+ 57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
104
+ 486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
105
+ 4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
106
+ 380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
107
+ 2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
108
+ 42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
109
+ 8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
110
+ 6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
111
+ b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
112
+ 9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
113
+ d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
114
+ 7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
115
+ 5b578fdfe33ac372e6'''.split())
116
+
117
+
118
+ def test_hex_pi_nth_digits():
119
+ assert pi_hex_digits(0) == '3243f6a8885a30'
120
+ assert pi_hex_digits(1) == '243f6a8885a308'
121
+ assert pi_hex_digits(10000) == '68ac8fcfb8016c'
122
+ assert pi_hex_digits(13) == '08d313198a2e03'
123
+ assert pi_hex_digits(0, 3) == '324'
124
+ assert pi_hex_digits(0, 0) == ''
125
+ raises(ValueError, lambda: pi_hex_digits(-1))
126
+ raises(ValueError, lambda: pi_hex_digits(0, -1))
127
+ raises(ValueError, lambda: pi_hex_digits(3.14))
128
+
129
+ # this will pick a random segment to compute every time
130
+ # it is run. If it ever fails, there is an error in the
131
+ # computation.
132
+ n = randint(0, len(dig))
133
+ prec = randint(0, len(dig) - n)
134
+ assert pi_hex_digits(n, prec) == dig[n: n + prec]
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_continued_fraction.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from sympy.core import GoldenRatio as phi
3
+ from sympy.core.numbers import (Rational, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.ntheory.continued_fraction import \
7
+ (continued_fraction_periodic as cf_p,
8
+ continued_fraction_iterator as cf_i,
9
+ continued_fraction_convergents as cf_c,
10
+ continued_fraction_reduce as cf_r,
11
+ continued_fraction as cf)
12
+ from sympy.testing.pytest import raises
13
+
14
+
15
+ def test_continued_fraction():
16
+ assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1)
17
+ assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1)
18
+ t = sqrt(2)
19
+ assert cf((1 + t)*(1 - t)) == cf(-1)
20
+ for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5,
21
+ (2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]:
22
+ assert (cf_r(cf(n)) - n).expand() == 0
23
+ assert (cf_r(cf(-n)) + n).expand() == 0
24
+ raises(ValueError, lambda: cf(sqrt(2 + sqrt(3))))
25
+ raises(ValueError, lambda: cf(sqrt(2) + sqrt(3)))
26
+ raises(ValueError, lambda: cf(pi))
27
+ raises(ValueError, lambda: cf(.1))
28
+
29
+ raises(ValueError, lambda: cf_p(1, 0, 0))
30
+ raises(ValueError, lambda: cf_p(1, 1, -1))
31
+ assert cf_p(4, 3, 0) == [1, 3]
32
+ assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
33
+ assert cf_p(1, 1, 0) == [1]
34
+ assert cf_p(3, 4, 0) == [0, 1, 3]
35
+ assert cf_p(4, 5, 0) == [0, 1, 4]
36
+ assert cf_p(5, 6, 0) == [0, 1, 5]
37
+ assert cf_p(11, 13, 0) == [0, 1, 5, 2]
38
+ assert cf_p(16, 19, 0) == [0, 1, 5, 3]
39
+ assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
40
+ assert cf_p(1, 2, 5) == [[1]]
41
+ assert cf_p(0, 1, 2) == [1, [2]]
42
+ assert cf_p(6, 7, 49) == [1, 1, 6]
43
+ assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
44
+ assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
45
+ assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
46
+ assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
47
+
48
+ def take(iterator, n=7):
49
+ return list(itertools.islice(iterator, n))
50
+
51
+ assert take(cf_i(phi)) == [1, 1, 1, 1, 1, 1, 1]
52
+ assert take(cf_i(pi)) == [3, 7, 15, 1, 292, 1, 1]
53
+
54
+ assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2]
55
+ assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2]
56
+
57
+ assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)]
58
+ assert list(cf_c([2])) == [S(2)]
59
+ assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3),
60
+ Rational(8, 5), Rational(13, 8), Rational(21, 13)]
61
+ assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)]
62
+ assert take(cf_c([[1]])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), Rational(8, 5),
63
+ Rational(13, 8), Rational(21, 13)]
64
+ assert take(cf_c([1, [1, 2]])) == [S.One, S(2), Rational(5, 3), Rational(7, 4), Rational(19, 11),
65
+ Rational(26, 15), Rational(71, 41)]
66
+
67
+ cf_iter_e = (2 if i == 1 else i // 3 * 2 if i % 3 == 0 else 1 for i in itertools.count(1))
68
+ assert take(cf_c(cf_iter_e)) == [S(2), S(3), Rational(8, 3), Rational(11, 4), Rational(19, 7),
69
+ Rational(87, 32), Rational(106, 39)]
70
+
71
+ assert cf_r([1, 6, 1, 8]) == Rational(71, 62)
72
+ assert cf_r([3]) == S(3)
73
+ assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29)
74
+ assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
75
+ assert cf_r([1, 5, 9]) == Rational(55, 46)
76
+ assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
77
+ assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2)
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_digits.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory import count_digits, digits, is_palindromic
2
+ from sympy.core.intfunc import num_digits
3
+
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ def test_num_digits():
8
+ # depending on whether one rounds up or down or uses log or log10,
9
+ # one or more of these will fail if you don't check for the off-by
10
+ # one condition
11
+ assert num_digits(2, 2) == 2
12
+ assert num_digits(2**48 - 1, 2) == 48
13
+ assert num_digits(1000, 10) == 4
14
+ assert num_digits(125, 5) == 4
15
+ assert num_digits(100, 16) == 2
16
+ assert num_digits(-1000, 10) == 4
17
+ # if changes are made to the function, this structured test over
18
+ # this range will expose problems
19
+ for base in range(2, 100):
20
+ for e in range(1, 100):
21
+ n = base**e
22
+ assert num_digits(n, base) == e + 1
23
+ assert num_digits(n + 1, base) == e + 1
24
+ assert num_digits(n - 1, base) == e
25
+
26
+
27
+ def test_digits():
28
+ assert all(digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
29
+ for n in range(20))
30
+ assert all(digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
31
+ for n in range(20))
32
+ assert all(digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
33
+ for n in range(20))
34
+ assert digits(2345, 34) == [34, 2, 0, 33]
35
+ assert digits(384753, 71) == [71, 1, 5, 23, 4]
36
+ assert digits(93409, 10) == [10, 9, 3, 4, 0, 9]
37
+ assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
38
+ assert digits(35, 10) == [10, 3, 5]
39
+ assert digits(35, 10, 3) == [10, 0, 3, 5]
40
+ assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5]
41
+ raises(ValueError, lambda: digits(2, 2, 1))
42
+
43
+
44
+ def test_count_digits():
45
+ assert count_digits(55, 2) == {1: 5, 0: 1}
46
+ assert count_digits(55, 10) == {5: 2}
47
+ n = count_digits(123)
48
+ assert n[4] == 0 and type(n[4]) is int
49
+
50
+
51
+ def test_is_palindromic():
52
+ assert is_palindromic(-11)
53
+ assert is_palindromic(11)
54
+ assert is_palindromic(0o121, 8)
55
+ assert not is_palindromic(123)
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_ecm.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external.gmpy import invert
2
+ from sympy.ntheory.ecm import ecm, Point
3
+ from sympy.testing.pytest import slow
4
+
5
+ @slow
6
+ def test_ecm():
7
+ assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297}
8
+ assert ecm(46167045131415113) == {43, 2634823, 407485517}
9
+ assert ecm(631211032315670776841) == {9312934919, 67777885039}
10
+ assert ecm(398883434337287) == {99476569, 4009823}
11
+ assert ecm(64211816600515193) == {281719, 359641, 633767}
12
+ assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123}
13
+ assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571}
14
+ assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803}
15
+ assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721}
16
+ #This takes ~10secs while factorint is not able to factorize this even in ~10mins
17
+ assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809}
18
+
19
+
20
+ def test_Point():
21
+ #The curve is of the form y**2 = x**3 + a*x**2 + x
22
+ mod = 101
23
+ a = 10
24
+ a_24 = (a + 2)*invert(4, mod)
25
+ p1 = Point(10, 17, a_24, mod)
26
+ p2 = p1.double()
27
+ assert p2 == Point(68, 56, a_24, mod)
28
+ p4 = p2.double()
29
+ assert p4 == Point(22, 64, a_24, mod)
30
+ p8 = p4.double()
31
+ assert p8 == Point(71, 95, a_24, mod)
32
+ p16 = p8.double()
33
+ assert p16 == Point(5, 16, a_24, mod)
34
+ p32 = p16.double()
35
+ assert p32 == Point(33, 96, a_24, mod)
36
+
37
+ # p3 = p2 + p1
38
+ p3 = p2.add(p1, p1)
39
+ assert p3 == Point(1, 61, a_24, mod)
40
+ # p5 = p3 + p2 or p4 + p1
41
+ p5 = p3.add(p2, p1)
42
+ assert p5 == Point(49, 90, a_24, mod)
43
+ assert p5 == p4.add(p1, p3)
44
+ # p6 = 2*p3
45
+ p6 = p3.double()
46
+ assert p6 == Point(87, 43, a_24, mod)
47
+ assert p6 == p4.add(p2, p2)
48
+ # p7 = p5 + p2
49
+ p7 = p5.add(p2, p3)
50
+ assert p7 == Point(69, 23, a_24, mod)
51
+ assert p7 == p4.add(p3, p1)
52
+ assert p7 == p6.add(p1, p5)
53
+ # p9 = p5 + p4
54
+ p9 = p5.add(p4, p1)
55
+ assert p9 == Point(56, 99, a_24, mod)
56
+ assert p9 == p6.add(p3, p3)
57
+ assert p9 == p7.add(p2, p5)
58
+ assert p9 == p8.add(p1, p7)
59
+
60
+ assert p5 == p1.mont_ladder(5)
61
+ assert p9 == p1.mont_ladder(9)
62
+ assert p16 == p1.mont_ladder(16)
63
+ assert p9 == p3.mont_ladder(3)
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.ntheory.egyptian_fraction import egyptian_fraction
3
+ from sympy.core.add import Add
4
+ from sympy.testing.pytest import raises
5
+ from sympy.core.random import random_complex_number
6
+
7
+
8
+ def test_egyptian_fraction():
9
+ def test_equality(r, alg="Greedy"):
10
+ return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)])
11
+
12
+ r = random_complex_number(a=0, c=1, b=0, d=0, rational=True)
13
+ assert test_equality(r)
14
+
15
+ assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345]
16
+ assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26]
17
+ assert egyptian_fraction(Rational(23, 101), "Greedy") == \
18
+ [5, 37, 1438, 2985448, 40108045937720]
19
+ assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \
20
+ [2, 6, 12, 35, 276, 2415]
21
+ assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \
22
+ [6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807,
23
+ 1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443,
24
+ 3267056, 3581556, 10192056, 10650056950806]
25
+ assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30]
26
+ assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737]
27
+ raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9)))
28
+ assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7,
29
+ 14, 574, 2788, 6460,
30
+ 11590, 33062, 113820]
31
+ assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9,
32
+ 10, 11, 12, 27, 744, 893588,
33
+ 1251493536607,
34
+ 20361068938197002344405230]
35
+
36
+
37
+ def test_input():
38
+ r = (2,3), Rational(2, 3), (Rational(2), Rational(3))
39
+ for m in ["Greedy", "Graham Jewett", "Takenouchi", "Golomb"]:
40
+ for i in r:
41
+ d = egyptian_fraction(i, m)
42
+ assert all(i.is_Integer for i in d)
43
+ if m == "Graham Jewett":
44
+ assert d == [3, 4, 12]
45
+ else:
46
+ assert d == [2, 6]
47
+ # check prefix
48
+ d = egyptian_fraction(Rational(5, 3))
49
+ assert d == [1, 2, 6] and all(i.is_Integer for i in d)
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_elliptic_curve.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.elliptic_curve import EllipticCurve
2
+
3
+
4
+ def test_elliptic_curve():
5
+ # Point addition and multiplication
6
+ e3 = EllipticCurve(-1, 9)
7
+ p = e3(0, 3)
8
+ q = e3(-1, 3)
9
+ r = p + q
10
+ assert r.x == 1 and r.y == -3
11
+ r = 2*p + q
12
+ assert r.x == 35 and r.y == 207
13
+ r = -p + q
14
+ assert r.x == 37 and r.y == 225
15
+ # Verify result in http://www.lmfdb.org/EllipticCurve/Q
16
+ # Discriminant
17
+ assert EllipticCurve(-1, 9).discriminant == -34928
18
+ assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088
19
+ # Torsion points
20
+ assert len(EllipticCurve(0, 1).torsion_points()) == 6
.venv/lib/python3.12/site-packages/sympy/ntheory/tests/test_factor_.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Dict
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.power import Pow
4
+ from sympy.core.singleton import S
5
+ from sympy.functions.combinatorial.factorials import factorial as fac
6
+ from sympy.core.numbers import Integer, Rational
7
+ from sympy.external.gmpy import gcd
8
+
9
+ from sympy.ntheory import (totient,
10
+ factorint, primefactors, divisors, nextprime,
11
+ pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial,
12
+ divisor_count, primorial, pollard_pm1, divisor_sigma,
13
+ factorrat, reduced_totient)
14
+ from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors,
15
+ antidivisors, antidivisor_count, _divisor_sigma, core, udivisors, udivisor_sigma,
16
+ udivisor_count, proper_divisor_count, primenu, primeomega,
17
+ mersenne_prime_exponent, is_perfect, is_abundant,
18
+ is_deficient, is_amicable, is_carmichael, find_carmichael_numbers_in_range,
19
+ find_first_n_carmichaels, dra, drm, _perfect_power, factor_cache)
20
+
21
+ from sympy.testing.pytest import raises, slow
22
+
23
+ from sympy.utilities.iterables import capture
24
+
25
+
26
+ def fac_multiplicity(n, p):
27
+ """Return the power of the prime number p in the
28
+ factorization of n!"""
29
+ if p > n:
30
+ return 0
31
+ if p > n//2:
32
+ return 1
33
+ q, m = n, 0
34
+ while q >= p:
35
+ q //= p
36
+ m += q
37
+ return m
38
+
39
+
40
+ def multiproduct(seq=(), start=1):
41
+ """
42
+ Return the product of a sequence of factors with multiplicities,
43
+ times the value of the parameter ``start``. The input may be a
44
+ sequence of (factor, exponent) pairs or a dict of such pairs.
45
+
46
+ >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
47
+ 279936
48
+
49
+ """
50
+ if not seq:
51
+ return start
52
+ if isinstance(seq, dict):
53
+ seq = iter(seq.items())
54
+ units = start
55
+ multi = []
56
+ for base, exp in seq:
57
+ if not exp:
58
+ continue
59
+ elif exp == 1:
60
+ units *= base
61
+ else:
62
+ if exp % 2:
63
+ units *= base
64
+ multi.append((base, exp//2))
65
+ return units * multiproduct(multi)**2
66
+
67
+
68
+ def test_multiplicity():
69
+ for b in range(2, 20):
70
+ for i in range(100):
71
+ assert multiplicity(b, b**i) == i
72
+ assert multiplicity(b, (b**i) * 23) == i
73
+ assert multiplicity(b, (b**i) * 1000249) == i
74
+ # Should be fast
75
+ assert multiplicity(10, 10**10023) == 10023
76
+ # Should exit quickly
77
+ assert multiplicity(10**10, 10**10) == 1
78
+ # Should raise errors for bad input
79
+ raises(ValueError, lambda: multiplicity(1, 1))
80
+ raises(ValueError, lambda: multiplicity(1, 2))
81
+ raises(ValueError, lambda: multiplicity(1.3, 2))
82
+ raises(ValueError, lambda: multiplicity(2, 0))
83
+ raises(ValueError, lambda: multiplicity(1.3, 0))
84
+
85
+ # handles Rationals
86
+ assert multiplicity(10, Rational(30, 7)) == 1
87
+ assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
88
+ assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
89
+ assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
90
+ assert multiplicity(3, Rational(1, 9)) == -2
91
+
92
+
93
+ def test_multiplicity_in_factorial():
94
+ n = fac(1000)
95
+ for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96):
96
+ assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000)
97
+
98
+
99
+ def test_private_perfect_power():
100
+ assert _perfect_power(0) is False
101
+ assert _perfect_power(1) is False
102
+ assert _perfect_power(2) is False
103
+ assert _perfect_power(3) is False
104
+ for x in [2, 3, 5, 6, 7, 12, 15, 105, 100003]:
105
+ for y in range(2, 100):
106
+ assert _perfect_power(x**y) == (x, y)
107
+ if x & 1:
108
+ assert _perfect_power(x**y, next_p=3) == (x, y)
109
+ if x == 100003:
110
+ assert _perfect_power(x**y, next_p=100003) == (x, y)
111
+ assert _perfect_power(101*x**y) == False
112
+ # Catalan's conjecture
113
+ if x**y not in [8, 9]:
114
+ assert _perfect_power(x**y + 1) == False
115
+ assert _perfect_power(x**y - 1) == False
116
+ for x in range(1, 10):
117
+ for y in range(1, 10):
118
+ g = gcd(x, y)
119
+ if g == 1:
120
+ assert _perfect_power(5**x * 101**y) == False
121
+ else:
122
+ assert _perfect_power(5**x * 101**y) == (5**(x//g) * 101**(y//g), g)
123
+
124
+
125
+ def test_perfect_power():
126
+ raises(ValueError, lambda: perfect_power(0.1))
127
+ assert perfect_power(0) is False
128
+ assert perfect_power(1) is False
129
+ assert perfect_power(2) is False
130
+ assert perfect_power(3) is False
131
+ assert perfect_power(4) == (2, 2)
132
+ assert perfect_power(14) is False
133
+ assert perfect_power(25) == (5, 2)
134
+ assert perfect_power(22) is False
135
+ assert perfect_power(22, [2]) is False
136
+ assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
137
+ assert perfect_power(137**(3*5*13) + 1) is False
138
+ assert perfect_power(137**(3*5*13) - 1) is False
139
+ assert perfect_power(103005006004**7) == (103005006004, 7)
140
+ assert perfect_power(103005006004**7 + 1) is False
141
+ assert perfect_power(103005006004**7 - 1) is False
142
+ assert perfect_power(103005006004**12) == (103005006004, 12)
143
+ assert perfect_power(103005006004**12 + 1) is False
144
+ assert perfect_power(103005006004**12 - 1) is False
145
+ assert perfect_power(2**10007) == (2, 10007)
146
+ assert perfect_power(2**10007 + 1) is False
147
+ assert perfect_power(2**10007 - 1) is False
148
+ assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
149
+ assert perfect_power((9**99 + 1)**60 + 1) is False
150
+ assert perfect_power((9**99 + 1)**60 - 1) is False
151
+ assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
152
+ assert perfect_power(10**100000) == (10, 100000)
153
+ assert perfect_power(10**100001) == (10, 100001)
154
+ assert perfect_power(13**4, [3, 5]) is False
155
+ assert perfect_power(3**4, [3, 10], factor=0) is False
156
+ assert perfect_power(3**3*5**3) == (15, 3)
157
+ assert perfect_power(2**3*5**5) is False
158
+ assert perfect_power(2*13**4) is False
159
+ assert perfect_power(2**5*3**3) is False
160
+ t = 2**24
161
+ for d in divisors(24):
162
+ m = perfect_power(t*3**d)
163
+ assert m and m[1] == d or d == 1
164
+ m = perfect_power(t*3**d, big=False)
165
+ assert m and m[1] == 2 or d == 1 or d == 3, (d, m)
166
+
167
+ # negatives and non-integer rationals
168
+ assert perfect_power(-4) is False
169
+ assert perfect_power(-8) == (-2, 3)
170
+ assert perfect_power(-S(1)/8) == (-S(1)/2, 3)
171
+ assert perfect_power(S(1)/3) == False
172
+ assert perfect_power(-5**15) == (-5, 15)
173
+ assert perfect_power(-5**15, big=False) == (-3125, 3)
174
+ assert perfect_power(-5**15, [15]) == (-5, 15)
175
+
176
+ n = -3 ** 60
177
+ assert perfect_power(n) == (-81, 15)
178
+ assert perfect_power(n, big=False) == (-3486784401, 3)
179
+ assert perfect_power(n, [3, 5], big=True) == (-531441, 5)
180
+ assert perfect_power(n, [3, 5], big=False) == (-3486784401, 3)
181
+ assert perfect_power(n, [2]) == False
182
+ assert perfect_power(n, [2, 15]) == (-81, 15)
183
+ assert perfect_power(n, [2, 13]) == False
184
+ assert perfect_power(n, [17]) == False
185
+ assert perfect_power(n, [3]) == (-3486784401, 3)
186
+ assert perfect_power(n + 1) == False
187
+
188
+ r = S(2) ** (2 * 5 * 7) / S(3) ** (2 * 7)
189
+ assert perfect_power(r) == (S(32) / 3, 14)
190
+ assert perfect_power(-r) == (-S(1024) / 9, 7)
191
+ assert perfect_power(r, big=False) == (S(34359738368) / 2187, 2)
192
+ assert perfect_power(r, [2, 5]) == (S(34359738368) / 2187, 2)
193
+ assert perfect_power(r, [5, 7]) == (S(1024) / 9, 7)
194
+ assert perfect_power(r, [5, 7], big=False) == (S(1024) / 9, 7)
195
+ assert perfect_power(r, [2, 5, 7], big=False) == (S(34359738368) / 2187, 2)
196
+ assert perfect_power(-r, [5, 7], big=False) == (-S(1024) / 9, 7)
197
+
198
+ assert perfect_power(-S(1) / 8) == (-S(1) / 2, 3)
199
+
200
+ assert perfect_power((-3)**60) == (3, 60)
201
+ assert perfect_power((-3)**61) == (-3, 61)
202
+
203
+ assert perfect_power(S(2 ** 9) / 3 ** 12) == (S(8)/81, 3)
204
+ assert perfect_power(Rational(1, 2)**3) == (S.Half, 3)
205
+ assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3)
206
+
207
+
208
+ def test_factor_cache():
209
+ factor_cache.cache_clear()
210
+ raises(ValueError, lambda: factor_cache.__setitem__(1, 5))
211
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 1))
212
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 10))
213
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 3))
214
+ raises(ValueError, lambda: factor_cache.__setitem__(20, 4))
215
+ factor_cache.maxsize = 3
216
+ for i in range(2, 10):
217
+ factor_cache[5*i] = 5
218
+ assert len(factor_cache) == 3
219
+ factor_cache.maxsize = 5
220
+ for i in range(2, 10):
221
+ factor_cache[5*i] = 5
222
+ assert len(factor_cache) == 5
223
+ factor_cache.maxsize = 2
224
+ assert len(factor_cache) == 2
225
+ factor_cache.maxsize =1000
226
+
227
+ factor_cache.cache_clear()
228
+ factor_cache[40] = 5
229
+ assert factor_cache.get(40) == 5
230
+ assert factor_cache.get(20) is None
231
+ assert factor_cache[40] == 5
232
+ raises(KeyError, lambda: factor_cache[10])
233
+ del factor_cache[40]
234
+ assert len(factor_cache) == 0
235
+ raises(KeyError, lambda: factor_cache.__delitem__(40))
236
+ factor_cache.add(100, [5, 2])
237
+ assert len(factor_cache) == 2
238
+ assert factor_cache[100] == 5
239
+
240
+ for n in [1000000007, 10000019*20000003]:
241
+ factorint(n)
242
+ assert n in factor_cache
243
+
244
+ # Restore the initial state
245
+ factor_cache.cache_clear()
246
+ factor_cache.maxsize = 1000
247
+
248
+
249
+ @slow
250
+ def test_factorint():
251
+ assert primefactors(123456) == [2, 3, 643]
252
+ assert factorint(0) == {0: 1}
253
+ assert factorint(1) == {}
254
+ assert factorint(-1) == {-1: 1}
255
+ assert factorint(-2) == {-1: 1, 2: 1}
256
+ assert factorint(-16) == {-1: 1, 2: 4}
257
+ assert factorint(2) == {2: 1}
258
+ assert factorint(126) == {2: 1, 3: 2, 7: 1}
259
+ assert factorint(123456) == {2: 6, 3: 1, 643: 1}
260
+ assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
261
+ assert factorint(64015937) == {7993: 1, 8009: 1}
262
+ assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
263
+ #issue 19683
264
+ assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
265
+ #issue 17676
266
+ assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
267
+ assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
268
+ assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}
269
+
270
+ assert factorint(0, multiple=True) == [0]
271
+ assert factorint(1, multiple=True) == []
272
+ assert factorint(-1, multiple=True) == [-1]
273
+ assert factorint(-2, multiple=True) == [-1, 2]
274
+ assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
275
+ assert factorint(2, multiple=True) == [2]
276
+ assert factorint(24, multiple=True) == [2, 2, 2, 3]
277
+ assert factorint(126, multiple=True) == [2, 3, 3, 7]
278
+ assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
279
+ assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
280
+ assert factorint(64015937, multiple=True) == [7993, 8009]
281
+ assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
282
+
283
+ assert factorint(fac(1, evaluate=False)) == {}
284
+ assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
285
+ assert factorint(fac(15, evaluate=False)) == \
286
+ {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
287
+ assert factorint(fac(20, evaluate=False)) == \
288
+ {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
289
+ assert factorint(fac(23, evaluate=False)) == \
290
+ {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}
291
+
292
+ assert multiproduct(factorint(fac(200))) == fac(200)
293
+ assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
294
+ for b, e in factorint(fac(150)).items():
295
+ assert e == fac_multiplicity(150, b)
296
+ for b, e in factorint(fac(150, evaluate=False)).items():
297
+ assert e == fac_multiplicity(150, b)
298
+ assert factorint(103005006059**7) == {103005006059: 7}
299
+ assert factorint(31337**191) == {31337: 191}
300
+ assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
301
+ {2: 1000, 3: 500, 257: 127, 383: 60}
302
+ assert len(factorint(fac(10000))) == 1229
303
+ assert len(factorint(fac(10000, evaluate=False))) == 1229
304
+ assert factorint(12932983746293756928584532764589230) == \
305
+ {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
306
+ assert factorint(727719592270351) == {727719592270351: 1}
307
+ assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
308
+ for n in range(60000):
309
+ assert multiproduct(factorint(n)) == n
310
+ assert pollard_rho(2**64 + 1, seed=1) == 274177
311
+ assert pollard_rho(19, seed=1) is None
312
+ assert factorint(3, limit=2) == {3: 1}
313
+ assert factorint(12345) == {3: 1, 5: 1, 823: 1}
314
+ assert factorint(
315
+ 12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit
316
+ assert factorint(1, limit=1) == {}
317
+ assert factorint(0, 3) == {0: 1}
318
+ assert factorint(12, limit=1) == {12: 1}
319
+ assert factorint(30, limit=2) == {2: 1, 15: 1}
320
+ assert factorint(16, limit=2) == {2: 4}
321
+ assert factorint(124, limit=3) == {2: 2, 31: 1}
322
+ assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
323
+ p1 = nextprime(2**32)
324
+ p2 = nextprime(2**16)
325
+ p3 = nextprime(p2)
326
+ assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
327
+ assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
328
+ assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
329
+ assert factorint(primorial(17) + 1, use_pm1=0) == \
330
+ {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
331
+ # when prime b is closer than approx sqrt(8*p) to prime p then they are
332
+ # "close" and have a trivial factorization
333
+ a = nextprime(2**2**8) # 78 digits
334
+ b = nextprime(a + 2**2**4)
335
+ assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
336
+
337
+ raises(ValueError, lambda: pollard_rho(4))
338
+ raises(ValueError, lambda: pollard_pm1(3))
339
+ raises(ValueError, lambda: pollard_pm1(10, B=2))
340
+ # verbose coverage
341
+ n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
342
+ assert 'with primes' in capture(lambda: factorint(n, verbose=1))
343
+ capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
344
+
345
+ n = nextprime(2**17)
346
+ capture(lambda: factorint(n**3, verbose=1)) # perfect power termination
347
+ capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg
348
+
349
+ # exceed 1st
350
+ n = nextprime(2**17)
351
+ n *= nextprime(n)
352
+ assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
353
+ n *= nextprime(n)
354
+ assert len(factorint(n)) == 3
355
+ assert len(factorint(n, limit=p1)) == 3
356
+ n *= nextprime(2*n)
357
+ # exceed 2nd
358
+ assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
359
+ assert capture(
360
+ lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
361
+ # non-prime pm1 result
362
+ n = nextprime(8069)
363
+ n *= nextprime(2*n)*nextprime(2*n, 2)
364
+ capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result
365
+ # factor fermat composite
366
+ p1 = nextprime(2**17)
367
+ p2 = nextprime(2*p1)
368
+ assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
369
+ # Test for non integer input
370
+ raises(ValueError, lambda: factorint(4.5))
371
+ # test dict/Dict input
372
+ sans = '2**10*3**3'
373
+ n = {4: 2, 12: 3}
374
+ assert str(factorint(n)) == sans
375
+ assert str(factorint(Dict(n))) == sans
376
+
377
+
378
+ def test_divisors_and_divisor_count():
379
+ assert divisors(-1) == [1]
380
+ assert divisors(0) == []
381
+ assert divisors(1) == [1]
382
+ assert divisors(2) == [1, 2]
383
+ assert divisors(3) == [1, 3]
384
+ assert divisors(17) == [1, 17]
385
+ assert divisors(10) == [1, 2, 5, 10]
386
+ assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
387
+ assert divisors(101) == [1, 101]
388
+ assert type(divisors(2, generator=True)) is not list
389
+
390
+ assert divisor_count(0) == 0
391
+ assert divisor_count(-1) == 1
392
+ assert divisor_count(1) == 1
393
+ assert divisor_count(6) == 4
394
+ assert divisor_count(12) == 6
395
+
396
+ assert divisor_count(180, 3) == divisor_count(180//3)
397
+ assert divisor_count(2*3*5, 7) == 0
398
+
399
+
400
+ def test_proper_divisors_and_proper_divisor_count():
401
+ assert proper_divisors(-1) == []
402
+ assert proper_divisors(0) == []
403
+ assert proper_divisors(1) == []
404
+ assert proper_divisors(2) == [1]
405
+ assert proper_divisors(3) == [1]
406
+ assert proper_divisors(17) == [1]
407
+ assert proper_divisors(10) == [1, 2, 5]
408
+ assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50]
409
+ assert proper_divisors(1000000007) == [1]
410
+ assert type(proper_divisors(2, generator=True)) is not list
411
+
412
+ assert proper_divisor_count(0) == 0
413
+ assert proper_divisor_count(-1) == 0
414
+ assert proper_divisor_count(1) == 0
415
+ assert proper_divisor_count(36) == 8
416
+ assert proper_divisor_count(2*3*5) == 7
417
+
418
+
419
+ def test_udivisors_and_udivisor_count():
420
+ assert udivisors(-1) == [1]
421
+ assert udivisors(0) == []
422
+ assert udivisors(1) == [1]
423
+ assert udivisors(2) == [1, 2]
424
+ assert udivisors(3) == [1, 3]
425
+ assert udivisors(17) == [1, 17]
426
+ assert udivisors(10) == [1, 2, 5, 10]
427
+ assert udivisors(100) == [1, 4, 25, 100]
428
+ assert udivisors(101) == [1, 101]
429
+ assert udivisors(1000) == [1, 8, 125, 1000]
430
+ assert type(udivisors(2, generator=True)) is not list
431
+
432
+ assert udivisor_count(0) == 0
433
+ assert udivisor_count(-1) == 1
434
+ assert udivisor_count(1) == 1
435
+ assert udivisor_count(6) == 4
436
+ assert udivisor_count(12) == 4
437
+
438
+ assert udivisor_count(180) == 8
439
+ assert udivisor_count(2*3*5*7) == 16
440
+
441
+
442
+ def test_issue_6981():
443
+ S = set(divisors(4)).union(set(divisors(Integer(2))))
444
+ assert S == {1,2,4}
445
+
446
+
447
+ def test_issue_4356():
448
+ assert factorint(1030903) == {53: 2, 367: 1}
449
+
450
+
451
+ def test_divisors():
452
+ assert divisors(28) == [1, 2, 4, 7, 14, 28]
453
+ assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105]
454
+ assert divisors(0) == []
455
+
456
+
457
+ def test_divisor_count():
458
+ assert divisor_count(0) == 0
459
+ assert divisor_count(6) == 4
460
+
461
+
462
+ def test_proper_divisors():
463
+ assert proper_divisors(-1) == []
464
+ assert proper_divisors(28) == [1, 2, 4, 7, 14]
465
+ assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35]
466
+
467
+
468
+ def test_proper_divisor_count():
469
+ assert proper_divisor_count(6) == 3
470
+ assert proper_divisor_count(108) == 11
471
+
472
+
473
+ def test_antidivisors():
474
+ assert antidivisors(-1) == []
475
+ assert antidivisors(-3) == [2]
476
+ assert antidivisors(14) == [3, 4, 9]
477
+ assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
478
+ assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
479
+ assert antidivisors(393216) == [262144]
480
+ assert sorted(x for x in antidivisors(3*5*7, 1)) == \
481
+ [2, 6, 10, 11, 14, 19, 30, 42, 70]
482
+ assert antidivisors(1) == []
483
+ assert type(antidivisors(2, generator=True)) is not list
484
+
485
+ def test_antidivisor_count():
486
+ assert antidivisor_count(0) == 0
487
+ assert antidivisor_count(-1) == 0
488
+ assert antidivisor_count(-4) == 1
489
+ assert antidivisor_count(20) == 3
490
+ assert antidivisor_count(25) == 5
491
+ assert antidivisor_count(38) == 7
492
+ assert antidivisor_count(180) == 6
493
+ assert antidivisor_count(2*3*5) == 3
494
+
495
+
496
+ def test_smoothness_and_smoothness_p():
497
+ assert smoothness(1) == (1, 1)
498
+ assert smoothness(2**4*3**2) == (3, 16)
499
+
500
+ assert smoothness_p(10431, m=1) == \
501
+ (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
502
+ assert smoothness_p(10431) == \
503
+ (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
504
+ assert smoothness_p(10431, power=1) == \
505
+ (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
506
+ assert smoothness_p(21477639576571, visual=1) == \
507
+ 'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
508
+ 'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
509
+
510
+
511
+ def test_visual_factorint():
512
+ assert factorint(1, visual=1) == 1
513
+ forty2 = factorint(42, visual=True)
514
+ assert type(forty2) == Mul
515
+ assert str(forty2) == '2**1*3**1*7**1'
516
+ assert factorint(1, visual=True) is S.One
517
+ no = {"evaluate": False}
518
+ assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
519
+ Pow(3, 2, **no),
520
+ Pow(7, 2, **no), **no)
521
+ assert -1 in factorint(-42, visual=True).args
522
+
523
+
524
+ def test_factorrat():
525
+ assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
526
+ assert str(factorrat(Rational(1, 1), visual=True)) == '1'
527
+ assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
528
+ assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)'
529
+ assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)'
530
+
531
+ assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
532
+ assert factorrat(Rational(1, 1), multiple=True) == []
533
+ assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5]
534
+ assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5]
535
+ assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3]
536
+ assert factorrat(S(-25)/14/9, multiple=True) == \
537
+ [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5]
538
+
539
+
540
+ def test_visual_io():
541
+ sm = smoothness_p
542
+ fi = factorint
543
+ # with smoothness_p
544
+ n = 124
545
+ d = fi(n)
546
+ m = fi(d, visual=True)
547
+ t = sm(n)
548
+ s = sm(t)
549
+ for th in [d, s, t, n, m]:
550
+ assert sm(th, visual=True) == s
551
+ assert sm(th, visual=1) == s
552
+ for th in [d, s, t, n, m]:
553
+ assert sm(th, visual=False) == t
554
+ assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
555
+ assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
556
+
557
+ # with factorint
558
+ for th in [d, m, n]:
559
+ assert fi(th, visual=True) == m
560
+ assert fi(th, visual=1) == m
561
+ for th in [d, m, n]:
562
+ assert fi(th, visual=False) == d
563
+ assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
564
+ assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
565
+
566
+ # test reevaluation
567
+ no = {"evaluate": False}
568
+ assert sm({4: 2}, visual=False) == sm(16)
569
+ assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
570
+ visual=False) == sm(2**10)
571
+
572
+ assert fi({4: 2}, visual=False) == fi(16)
573
+ assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
574
+ visual=False) == fi(2**10)
575
+
576
+
577
+ def test_core():
578
+ assert core(35**13, 10) == 42875
579
+ assert core(210**2) == 1
580
+ assert core(7776, 3) == 36
581
+ assert core(10**27, 22) == 10**5
582
+ assert core(537824) == 14
583
+ assert core(1, 6) == 1
584
+
585
+
586
+ def test__divisor_sigma():
587
+ assert _divisor_sigma(23450) == 50592
588
+ assert _divisor_sigma(23450, 0) == 24
589
+ assert _divisor_sigma(23450, 1) == 50592
590
+ assert _divisor_sigma(23450, 2) == 730747500
591
+ assert _divisor_sigma(23450, 3) == 14666785333344
592
+ A000005 = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6, 4,
593
+ 4, 2, 8, 3, 4, 4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4, 8, 2, 8]
594
+ for n, val in enumerate(A000005, 1):
595
+ assert _divisor_sigma(n, 0) == val
596
+ A000203 = [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12, 28, 14, 24, 24, 31, 18,
597
+ 39, 20, 42, 32, 36, 24, 60, 31, 42, 40, 56, 30, 72, 32, 63, 48]
598
+ for n, val in enumerate(A000203, 1):
599
+ assert _divisor_sigma(n, 1) == val
600
+ A001157 = [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122, 210, 170, 250, 260,
601
+ 341, 290, 455, 362, 546, 500, 610, 530, 850, 651, 850, 820, 1050]
602
+ for n, val in enumerate(A001157, 1):
603
+ assert _divisor_sigma(n, 2) == val
604
+
605
+
606
+ def test_mersenne_prime_exponent():
607
+ assert mersenne_prime_exponent(1) == 2
608
+ assert mersenne_prime_exponent(4) == 7
609
+ assert mersenne_prime_exponent(10) == 89
610
+ assert mersenne_prime_exponent(25) == 21701
611
+ raises(ValueError, lambda: mersenne_prime_exponent(52))
612
+ raises(ValueError, lambda: mersenne_prime_exponent(0))
613
+
614
+
615
+ def test_is_perfect():
616
+ assert is_perfect(-6) is False
617
+ assert is_perfect(6) is True
618
+ assert is_perfect(15) is False
619
+ assert is_perfect(28) is True
620
+ assert is_perfect(400) is False
621
+ assert is_perfect(496) is True
622
+ assert is_perfect(8128) is True
623
+ assert is_perfect(10000) is False
624
+
625
+
626
+ def test_is_abundant():
627
+ assert is_abundant(10) is False
628
+ assert is_abundant(12) is True
629
+ assert is_abundant(18) is True
630
+ assert is_abundant(21) is False
631
+ assert is_abundant(945) is True
632
+
633
+
634
+ def test_is_deficient():
635
+ assert is_deficient(10) is True
636
+ assert is_deficient(22) is True
637
+ assert is_deficient(56) is False
638
+ assert is_deficient(20) is False
639
+ assert is_deficient(36) is False
640
+
641
+
642
+ def test_is_amicable():
643
+ assert is_amicable(173, 129) is False
644
+ assert is_amicable(220, 284) is True
645
+ assert is_amicable(8756, 8756) is False
646
+
647
+
648
+ def test_is_carmichael():
649
+ A002997 = [561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841,
650
+ 29341, 41041, 46657, 52633, 62745, 63973, 75361, 101101]
651
+ for n in range(1, 5000):
652
+ assert is_carmichael(n) == (n in A002997)
653
+ for n in A002997:
654
+ assert is_carmichael(n)
655
+
656
+
657
+ def test_find_carmichael_numbers_in_range():
658
+ assert find_carmichael_numbers_in_range(0, 561) == []
659
+ assert find_carmichael_numbers_in_range(561, 562) == [561]
660
+ assert find_carmichael_numbers_in_range(561, 1105) == find_carmichael_numbers_in_range(561, 562)
661
+ raises(ValueError, lambda: find_carmichael_numbers_in_range(-2, 2))
662
+ raises(ValueError, lambda: find_carmichael_numbers_in_range(22, 2))
663
+
664
+
665
+ def test_find_first_n_carmichaels():
666
+ assert find_first_n_carmichaels(0) == []
667
+ assert find_first_n_carmichaels(1) == [561]
668
+ assert find_first_n_carmichaels(2) == [561, 1105]
669
+
670
+
671
+ def test_dra():
672
+ assert dra(19, 12) == 8
673
+ assert dra(2718, 10) == 9
674
+ assert dra(0, 22) == 0
675
+ assert dra(23456789, 10) == 8
676
+ raises(ValueError, lambda: dra(24, -2))
677
+ raises(ValueError, lambda: dra(24.2, 5))
678
+
679
+ def test_drm():
680
+ assert drm(19, 12) == 7
681
+ assert drm(2718, 10) == 2
682
+ assert drm(0, 15) == 0
683
+ assert drm(234161, 10) == 6
684
+ raises(ValueError, lambda: drm(24, -2))
685
+ raises(ValueError, lambda: drm(11.6, 9))
686
+
687
+
688
+ def test_deprecated_ntheory_symbolic_functions():
689
+ from sympy.testing.pytest import warns_deprecated_sympy
690
+
691
+ with warns_deprecated_sympy():
692
+ assert primenu(3) == 1
693
+ with warns_deprecated_sympy():
694
+ assert primeomega(3) == 1
695
+ with warns_deprecated_sympy():
696
+ assert totient(3) == 2
697
+ with warns_deprecated_sympy():
698
+ assert reduced_totient(3) == 2
699
+ with warns_deprecated_sympy():
700
+ assert divisor_sigma(3) == 4
701
+ with warns_deprecated_sympy():
702
+ assert udivisor_sigma(3) == 4