Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/22.attention.dense.weight/exp_avg.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__init__.py +67 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py +159 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py +351 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/digits.py +143 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/ecm.py +326 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py +223 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py +398 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/factor_.py +2654 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/generate.py +1037 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/modular.py +255 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/multinomial.py +188 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/partitions_.py +192 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/primetest.py +696 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/qs.py +515 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py +1573 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py +133 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py +73 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py +34 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py +63 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py +49 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py +20 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py +685 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py +250 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py +34 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py +48 -0
- venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py +12 -0
ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:759ef16de4f66ff57d172baa9bd08877eb6575cb7cac5ca9f5885a7e50d02fbf
|
3 |
+
size 50332828
|
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cc6084cd345f44eb1642ce3391b398053ca70d8b6d0839cbe4d7720d42849fc1
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:908bf5a847cc190bf0103650e4cb7fdf9fbff917d301c06cb0024b1bd020c5ab
|
3 |
+
size 50332828
|
ckpts/universal/global_step80/zero/22.attention.dense.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5a848cd339f4c487c26491388a3b049bb50e4697038c776a11f496f0e577a80b
|
3 |
+
size 16778396
|
venv/lib/python3.10/site-packages/sympy/ntheory/__init__.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Number theory module (primes, etc)
|
3 |
+
"""
|
4 |
+
|
5 |
+
from .generate import nextprime, prevprime, prime, primepi, primerange, \
|
6 |
+
randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi
|
7 |
+
from .primetest import isprime, is_gaussian_prime
|
8 |
+
from .factor_ import divisors, proper_divisors, factorint, multiplicity, \
|
9 |
+
multiplicity_in_factorial, perfect_power, pollard_pm1, pollard_rho, \
|
10 |
+
primefactors, totient, trailing, \
|
11 |
+
divisor_count, proper_divisor_count, divisor_sigma, factorrat, \
|
12 |
+
reduced_totient, primenu, primeomega, mersenne_prime_exponent, \
|
13 |
+
is_perfect, is_mersenne_prime, is_abundant, is_deficient, is_amicable, \
|
14 |
+
abundance, dra, drm
|
15 |
+
|
16 |
+
from .partitions_ import npartitions
|
17 |
+
from .residue_ntheory import is_primitive_root, is_quad_residue, \
|
18 |
+
legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \
|
19 |
+
primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \
|
20 |
+
discrete_log, quadratic_congruence, polynomial_congruence
|
21 |
+
from .multinomial import binomial_coefficients, binomial_coefficients_list, \
|
22 |
+
multinomial_coefficients
|
23 |
+
from .continued_fraction import continued_fraction_periodic, \
|
24 |
+
continued_fraction_iterator, continued_fraction_reduce, \
|
25 |
+
continued_fraction_convergents, continued_fraction
|
26 |
+
from .digits import count_digits, digits, is_palindromic
|
27 |
+
from .egyptian_fraction import egyptian_fraction
|
28 |
+
from .ecm import ecm
|
29 |
+
from .qs import qs
|
30 |
+
__all__ = [
|
31 |
+
'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
|
32 |
+
'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
|
33 |
+
|
34 |
+
'isprime', 'is_gaussian_prime',
|
35 |
+
|
36 |
+
|
37 |
+
'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power',
|
38 |
+
'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', 'trailing',
|
39 |
+
'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat',
|
40 |
+
'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent',
|
41 |
+
'is_perfect', 'is_mersenne_prime', 'is_abundant', 'is_deficient', 'is_amicable',
|
42 |
+
'abundance', 'dra', 'drm', 'multiplicity_in_factorial',
|
43 |
+
|
44 |
+
'npartitions',
|
45 |
+
|
46 |
+
'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
|
47 |
+
'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
|
48 |
+
'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
|
49 |
+
'mobius', 'discrete_log', 'quadratic_congruence', 'polynomial_congruence',
|
50 |
+
|
51 |
+
'binomial_coefficients', 'binomial_coefficients_list',
|
52 |
+
'multinomial_coefficients',
|
53 |
+
|
54 |
+
'continued_fraction_periodic', 'continued_fraction_iterator',
|
55 |
+
'continued_fraction_reduce', 'continued_fraction_convergents',
|
56 |
+
'continued_fraction',
|
57 |
+
|
58 |
+
'digits',
|
59 |
+
'count_digits',
|
60 |
+
'is_palindromic',
|
61 |
+
|
62 |
+
'egyptian_fraction',
|
63 |
+
|
64 |
+
'ecm',
|
65 |
+
|
66 |
+
'qs',
|
67 |
+
]
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc
ADDED
Binary file (5.13 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc
ADDED
Binary file (3.89 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc
ADDED
Binary file (9.11 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc
ADDED
Binary file (6.54 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc
ADDED
Binary file (11.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc
ADDED
Binary file (4.51 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc
ADDED
Binary file (4.81 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc
ADDED
Binary file (15.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc
ADDED
Binary file (34.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import math
|
75 |
+
from sympy.utilities.misc import as_int
|
76 |
+
|
77 |
+
|
78 |
+
def _series(j, n, prec=14):
|
79 |
+
|
80 |
+
# Left sum from the bbp algorithm
|
81 |
+
s = 0
|
82 |
+
D = _dn(n, prec)
|
83 |
+
D4 = 4 * D
|
84 |
+
k = 0
|
85 |
+
d = 8 * k + j
|
86 |
+
for k in range(n + 1):
|
87 |
+
s += (pow(16, n - k, d) << D4) // d
|
88 |
+
d += 8
|
89 |
+
|
90 |
+
# Right sum iterates to infinity for full precision, but we
|
91 |
+
# stop at the point where one iteration is beyond the precision
|
92 |
+
# specified.
|
93 |
+
|
94 |
+
t = 0
|
95 |
+
k = n + 1
|
96 |
+
e = 4*(D + n - k)
|
97 |
+
d = 8 * k + j
|
98 |
+
while True:
|
99 |
+
dt = (1 << e) // d
|
100 |
+
if not dt:
|
101 |
+
break
|
102 |
+
t += dt
|
103 |
+
# k += 1
|
104 |
+
e -= 4
|
105 |
+
d += 8
|
106 |
+
total = s + t
|
107 |
+
|
108 |
+
return total
|
109 |
+
|
110 |
+
|
111 |
+
def pi_hex_digits(n, prec=14):
|
112 |
+
"""Returns a string containing ``prec`` (default 14) digits
|
113 |
+
starting at the nth digit of pi in hex. Counting of digits
|
114 |
+
starts at 0 and the decimal is not counted, so for n = 0 the
|
115 |
+
returned value starts with 3; n = 1 corresponds to the first
|
116 |
+
digit past the decimal point (which in hex is 2).
|
117 |
+
|
118 |
+
Examples
|
119 |
+
========
|
120 |
+
|
121 |
+
>>> from sympy.ntheory.bbp_pi import pi_hex_digits
|
122 |
+
>>> pi_hex_digits(0)
|
123 |
+
'3243f6a8885a30'
|
124 |
+
>>> pi_hex_digits(0, 3)
|
125 |
+
'324'
|
126 |
+
|
127 |
+
References
|
128 |
+
==========
|
129 |
+
|
130 |
+
.. [1] http://www.numberworld.org/digits/Pi/
|
131 |
+
"""
|
132 |
+
n, prec = as_int(n), as_int(prec)
|
133 |
+
if n < 0:
|
134 |
+
raise ValueError('n cannot be negative')
|
135 |
+
if prec == 0:
|
136 |
+
return ''
|
137 |
+
|
138 |
+
# main of implementation arrays holding formulae coefficients
|
139 |
+
n -= 1
|
140 |
+
a = [4, 2, 1, 1]
|
141 |
+
j = [1, 4, 5, 6]
|
142 |
+
|
143 |
+
#formulae
|
144 |
+
D = _dn(n, prec)
|
145 |
+
x = + (a[0]*_series(j[0], n, prec)
|
146 |
+
- a[1]*_series(j[1], n, prec)
|
147 |
+
- a[2]*_series(j[2], n, prec)
|
148 |
+
- a[3]*_series(j[3], n, prec)) & (16**D - 1)
|
149 |
+
|
150 |
+
s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
|
151 |
+
return s
|
152 |
+
|
153 |
+
|
154 |
+
def _dn(n, prec):
|
155 |
+
# controller for n dependence on precision
|
156 |
+
# n = starting digit index
|
157 |
+
# prec = the number of total digits to compute
|
158 |
+
n += 1 # because we subtract 1 for _series
|
159 |
+
return int(math.log(n + prec)/math.log(16) + prec + 3)
|
venv/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py
ADDED
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from sympy.core.exprtools import factor_terms
|
3 |
+
from sympy.core.numbers import Integer, Rational
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import Dummy
|
6 |
+
from sympy.core.sympify import _sympify
|
7 |
+
from sympy.utilities.misc import as_int
|
8 |
+
|
9 |
+
|
10 |
+
def continued_fraction(a) -> list:
|
11 |
+
"""Return the continued fraction representation of a Rational or
|
12 |
+
quadratic irrational.
|
13 |
+
|
14 |
+
Examples
|
15 |
+
========
|
16 |
+
|
17 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction
|
18 |
+
>>> from sympy import sqrt
|
19 |
+
>>> continued_fraction((1 + 2*sqrt(3))/5)
|
20 |
+
[0, 1, [8, 3, 34, 3]]
|
21 |
+
|
22 |
+
See Also
|
23 |
+
========
|
24 |
+
continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents
|
25 |
+
"""
|
26 |
+
e = _sympify(a)
|
27 |
+
if all(i.is_Rational for i in e.atoms()):
|
28 |
+
if e.is_Integer:
|
29 |
+
return continued_fraction_periodic(e, 1, 0)
|
30 |
+
elif e.is_Rational:
|
31 |
+
return continued_fraction_periodic(e.p, e.q, 0)
|
32 |
+
elif e.is_Pow and e.exp is S.Half and e.base.is_Integer:
|
33 |
+
return continued_fraction_periodic(0, 1, e.base)
|
34 |
+
elif e.is_Mul and len(e.args) == 2 and (
|
35 |
+
e.args[0].is_Rational and
|
36 |
+
e.args[1].is_Pow and
|
37 |
+
e.args[1].base.is_Integer and
|
38 |
+
e.args[1].exp is S.Half):
|
39 |
+
a, b = e.args
|
40 |
+
return continued_fraction_periodic(0, a.q, b.base, a.p)
|
41 |
+
else:
|
42 |
+
# this should not have to work very hard- no
|
43 |
+
# simplification, cancel, etc... which should be
|
44 |
+
# done by the user. e.g. This is a fancy 1 but
|
45 |
+
# the user should simplify it first:
|
46 |
+
# sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2)
|
47 |
+
p, d = e.expand().as_numer_denom()
|
48 |
+
if d.is_Integer:
|
49 |
+
if p.is_Rational:
|
50 |
+
return continued_fraction_periodic(p, d)
|
51 |
+
# look for a + b*c
|
52 |
+
# with c = sqrt(s)
|
53 |
+
if p.is_Add and len(p.args) == 2:
|
54 |
+
a, bc = p.args
|
55 |
+
else:
|
56 |
+
a = S.Zero
|
57 |
+
bc = p
|
58 |
+
if a.is_Integer:
|
59 |
+
b = S.NaN
|
60 |
+
if bc.is_Mul and len(bc.args) == 2:
|
61 |
+
b, c = bc.args
|
62 |
+
elif bc.is_Pow:
|
63 |
+
b = Integer(1)
|
64 |
+
c = bc
|
65 |
+
if b.is_Integer and (
|
66 |
+
c.is_Pow and c.exp is S.Half and
|
67 |
+
c.base.is_Integer):
|
68 |
+
# (a + b*sqrt(c))/d
|
69 |
+
c = c.base
|
70 |
+
return continued_fraction_periodic(a, d, c, b)
|
71 |
+
raise ValueError(
|
72 |
+
'expecting a rational or quadratic irrational, not %s' % e)
|
73 |
+
|
74 |
+
|
75 |
+
def continued_fraction_periodic(p, q, d=0, s=1) -> list:
|
76 |
+
r"""
|
77 |
+
Find the periodic continued fraction expansion of a quadratic irrational.
|
78 |
+
|
79 |
+
Compute the continued fraction expansion of a rational or a
|
80 |
+
quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where
|
81 |
+
`p`, `q \ne 0` and `d \ge 0` are integers.
|
82 |
+
|
83 |
+
Returns the continued fraction representation (canonical form) as
|
84 |
+
a list of integers, optionally ending (for quadratic irrationals)
|
85 |
+
with list of integers representing the repeating digits.
|
86 |
+
|
87 |
+
Parameters
|
88 |
+
==========
|
89 |
+
|
90 |
+
p : int
|
91 |
+
the rational part of the number's numerator
|
92 |
+
q : int
|
93 |
+
the denominator of the number
|
94 |
+
d : int, optional
|
95 |
+
the irrational part (discriminator) of the number's numerator
|
96 |
+
s : int, optional
|
97 |
+
the coefficient of the irrational part
|
98 |
+
|
99 |
+
Examples
|
100 |
+
========
|
101 |
+
|
102 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
|
103 |
+
>>> continued_fraction_periodic(3, 2, 7)
|
104 |
+
[2, [1, 4, 1, 1]]
|
105 |
+
|
106 |
+
Golden ratio has the simplest continued fraction expansion:
|
107 |
+
|
108 |
+
>>> continued_fraction_periodic(1, 2, 5)
|
109 |
+
[[1]]
|
110 |
+
|
111 |
+
If the discriminator is zero or a perfect square then the number will be a
|
112 |
+
rational number:
|
113 |
+
|
114 |
+
>>> continued_fraction_periodic(4, 3, 0)
|
115 |
+
[1, 3]
|
116 |
+
>>> continued_fraction_periodic(4, 3, 49)
|
117 |
+
[3, 1, 2]
|
118 |
+
|
119 |
+
See Also
|
120 |
+
========
|
121 |
+
|
122 |
+
continued_fraction_iterator, continued_fraction_reduce
|
123 |
+
|
124 |
+
References
|
125 |
+
==========
|
126 |
+
|
127 |
+
.. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction
|
128 |
+
.. [2] K. Rosen. Elementary Number theory and its applications.
|
129 |
+
Addison-Wesley, 3 Sub edition, pages 379-381, January 1992.
|
130 |
+
|
131 |
+
"""
|
132 |
+
from sympy.functions import sqrt, floor
|
133 |
+
|
134 |
+
p, q, d, s = list(map(as_int, [p, q, d, s]))
|
135 |
+
|
136 |
+
if d < 0:
|
137 |
+
raise ValueError("expected non-negative for `d` but got %s" % d)
|
138 |
+
|
139 |
+
if q == 0:
|
140 |
+
raise ValueError("The denominator cannot be 0.")
|
141 |
+
|
142 |
+
if not s:
|
143 |
+
d = 0
|
144 |
+
|
145 |
+
# check for rational case
|
146 |
+
sd = sqrt(d)
|
147 |
+
if sd.is_Integer:
|
148 |
+
return list(continued_fraction_iterator(Rational(p + s*sd, q)))
|
149 |
+
|
150 |
+
# irrational case with sd != Integer
|
151 |
+
if q < 0:
|
152 |
+
p, q, s = -p, -q, -s
|
153 |
+
|
154 |
+
n = (p + s*sd)/q
|
155 |
+
if n < 0:
|
156 |
+
w = floor(-n)
|
157 |
+
f = -n - w
|
158 |
+
one_f = continued_fraction(1 - f) # 1-f < 1 so cf is [0 ... [...]]
|
159 |
+
one_f[0] -= w + 1
|
160 |
+
return one_f
|
161 |
+
|
162 |
+
d *= s**2
|
163 |
+
sd *= s
|
164 |
+
|
165 |
+
if (d - p**2)%q:
|
166 |
+
d *= q**2
|
167 |
+
sd *= q
|
168 |
+
p *= q
|
169 |
+
q *= q
|
170 |
+
|
171 |
+
terms: list[int] = []
|
172 |
+
pq = {}
|
173 |
+
|
174 |
+
while (p, q) not in pq:
|
175 |
+
pq[(p, q)] = len(terms)
|
176 |
+
terms.append((p + sd)//q)
|
177 |
+
p = terms[-1]*q - p
|
178 |
+
q = (d - p**2)//q
|
179 |
+
|
180 |
+
i = pq[(p, q)]
|
181 |
+
return terms[:i] + [terms[i:]] # type: ignore
|
182 |
+
|
183 |
+
|
184 |
+
def continued_fraction_reduce(cf):
|
185 |
+
"""
|
186 |
+
Reduce a continued fraction to a rational or quadratic irrational.
|
187 |
+
|
188 |
+
Compute the rational or quadratic irrational number from its
|
189 |
+
terminating or periodic continued fraction expansion. The
|
190 |
+
continued fraction expansion (cf) should be supplied as a
|
191 |
+
terminating iterator supplying the terms of the expansion. For
|
192 |
+
terminating continued fractions, this is equivalent to
|
193 |
+
``list(continued_fraction_convergents(cf))[-1]``, only a little more
|
194 |
+
efficient. If the expansion has a repeating part, a list of the
|
195 |
+
repeating terms should be returned as the last element from the
|
196 |
+
iterator. This is the format returned by
|
197 |
+
continued_fraction_periodic.
|
198 |
+
|
199 |
+
For quadratic irrationals, returns the largest solution found,
|
200 |
+
which is generally the one sought, if the fraction is in canonical
|
201 |
+
form (all terms positive except possibly the first).
|
202 |
+
|
203 |
+
Examples
|
204 |
+
========
|
205 |
+
|
206 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_reduce
|
207 |
+
>>> continued_fraction_reduce([1, 2, 3, 4, 5])
|
208 |
+
225/157
|
209 |
+
>>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2])
|
210 |
+
-256/233
|
211 |
+
>>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10)
|
212 |
+
2.718281835
|
213 |
+
>>> continued_fraction_reduce([1, 4, 2, [3, 1]])
|
214 |
+
(sqrt(21) + 287)/238
|
215 |
+
>>> continued_fraction_reduce([[1]])
|
216 |
+
(1 + sqrt(5))/2
|
217 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
|
218 |
+
>>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13))
|
219 |
+
(sqrt(13) + 8)/5
|
220 |
+
|
221 |
+
See Also
|
222 |
+
========
|
223 |
+
|
224 |
+
continued_fraction_periodic
|
225 |
+
|
226 |
+
"""
|
227 |
+
from sympy.solvers import solve
|
228 |
+
|
229 |
+
period = []
|
230 |
+
x = Dummy('x')
|
231 |
+
|
232 |
+
def untillist(cf):
|
233 |
+
for nxt in cf:
|
234 |
+
if isinstance(nxt, list):
|
235 |
+
period.extend(nxt)
|
236 |
+
yield x
|
237 |
+
break
|
238 |
+
yield nxt
|
239 |
+
|
240 |
+
a = S.Zero
|
241 |
+
for a in continued_fraction_convergents(untillist(cf)):
|
242 |
+
pass
|
243 |
+
|
244 |
+
if period:
|
245 |
+
y = Dummy('y')
|
246 |
+
solns = solve(continued_fraction_reduce(period + [y]) - y, y)
|
247 |
+
solns.sort()
|
248 |
+
pure = solns[-1]
|
249 |
+
rv = a.subs(x, pure).radsimp()
|
250 |
+
else:
|
251 |
+
rv = a
|
252 |
+
if rv.is_Add:
|
253 |
+
rv = factor_terms(rv)
|
254 |
+
if rv.is_Mul and rv.args[0] == -1:
|
255 |
+
rv = rv.func(*rv.args)
|
256 |
+
return rv
|
257 |
+
|
258 |
+
|
259 |
+
def continued_fraction_iterator(x):
|
260 |
+
"""
|
261 |
+
Return continued fraction expansion of x as iterator.
|
262 |
+
|
263 |
+
Examples
|
264 |
+
========
|
265 |
+
|
266 |
+
>>> from sympy import Rational, pi
|
267 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_iterator
|
268 |
+
|
269 |
+
>>> list(continued_fraction_iterator(Rational(3, 8)))
|
270 |
+
[0, 2, 1, 2]
|
271 |
+
>>> list(continued_fraction_iterator(Rational(-3, 8)))
|
272 |
+
[-1, 1, 1, 1, 2]
|
273 |
+
|
274 |
+
>>> for i, v in enumerate(continued_fraction_iterator(pi)):
|
275 |
+
... if i > 7:
|
276 |
+
... break
|
277 |
+
... print(v)
|
278 |
+
3
|
279 |
+
7
|
280 |
+
15
|
281 |
+
1
|
282 |
+
292
|
283 |
+
1
|
284 |
+
1
|
285 |
+
1
|
286 |
+
|
287 |
+
References
|
288 |
+
==========
|
289 |
+
|
290 |
+
.. [1] https://en.wikipedia.org/wiki/Continued_fraction
|
291 |
+
|
292 |
+
"""
|
293 |
+
from sympy.functions import floor
|
294 |
+
while True:
|
295 |
+
i = floor(x)
|
296 |
+
yield i
|
297 |
+
x -= i
|
298 |
+
if not x:
|
299 |
+
break
|
300 |
+
x = 1/x
|
301 |
+
|
302 |
+
|
303 |
+
def continued_fraction_convergents(cf):
|
304 |
+
"""
|
305 |
+
Return an iterator over the convergents of a continued fraction (cf).
|
306 |
+
|
307 |
+
The parameter should be an iterable returning successive
|
308 |
+
partial quotients of the continued fraction, such as might be
|
309 |
+
returned by continued_fraction_iterator. In computing the
|
310 |
+
convergents, the continued fraction need not be strictly in
|
311 |
+
canonical form (all integers, all but the first positive).
|
312 |
+
Rational and negative elements may be present in the expansion.
|
313 |
+
|
314 |
+
Examples
|
315 |
+
========
|
316 |
+
|
317 |
+
>>> from sympy.core import pi
|
318 |
+
>>> from sympy import S
|
319 |
+
>>> from sympy.ntheory.continued_fraction import \
|
320 |
+
continued_fraction_convergents, continued_fraction_iterator
|
321 |
+
|
322 |
+
>>> list(continued_fraction_convergents([0, 2, 1, 2]))
|
323 |
+
[0, 1/2, 1/3, 3/8]
|
324 |
+
|
325 |
+
>>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')]))
|
326 |
+
[1, 3, 19/5, 7]
|
327 |
+
|
328 |
+
>>> it = continued_fraction_convergents(continued_fraction_iterator(pi))
|
329 |
+
>>> for n in range(7):
|
330 |
+
... print(next(it))
|
331 |
+
3
|
332 |
+
22/7
|
333 |
+
333/106
|
334 |
+
355/113
|
335 |
+
103993/33102
|
336 |
+
104348/33215
|
337 |
+
208341/66317
|
338 |
+
|
339 |
+
See Also
|
340 |
+
========
|
341 |
+
|
342 |
+
continued_fraction_iterator
|
343 |
+
|
344 |
+
"""
|
345 |
+
p_2, q_2 = S.Zero, S.One
|
346 |
+
p_1, q_1 = S.One, S.Zero
|
347 |
+
for a in cf:
|
348 |
+
p, q = a*p_1 + p_2, a*q_1 + q_2
|
349 |
+
p_2, q_2 = p_1, q_1
|
350 |
+
p_1, q_1 = p, q
|
351 |
+
yield p/q
|
venv/lib/python3.10/site-packages/sympy/ntheory/digits.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""
|
49 |
+
|
50 |
+
b = as_int(b)
|
51 |
+
n = as_int(n)
|
52 |
+
if b < 2:
|
53 |
+
raise ValueError("b must be greater than 1")
|
54 |
+
else:
|
55 |
+
x, y = abs(n), []
|
56 |
+
while x >= b:
|
57 |
+
x, r = divmod(x, b)
|
58 |
+
y.append(r)
|
59 |
+
y.append(x)
|
60 |
+
y.append(-b if n < 0 else b)
|
61 |
+
y.reverse()
|
62 |
+
ndig = len(y) - 1
|
63 |
+
if digits is not None:
|
64 |
+
if ndig > digits:
|
65 |
+
raise ValueError(
|
66 |
+
"For %s, at least %s digits are needed." % (n, ndig))
|
67 |
+
elif ndig < digits:
|
68 |
+
y[1:1] = [0]*(digits - ndig)
|
69 |
+
return y
|
70 |
+
|
71 |
+
|
72 |
+
def count_digits(n, b=10):
|
73 |
+
"""
|
74 |
+
Return a dictionary whose keys are the digits of ``n`` in the
|
75 |
+
given base, ``b``, with keys indicating the digits appearing in the
|
76 |
+
number and values indicating how many times that digit appeared.
|
77 |
+
|
78 |
+
Examples
|
79 |
+
========
|
80 |
+
|
81 |
+
>>> from sympy.ntheory import count_digits
|
82 |
+
|
83 |
+
>>> count_digits(1111339)
|
84 |
+
{1: 4, 3: 2, 9: 1}
|
85 |
+
|
86 |
+
The digits returned are always represented in base-10
|
87 |
+
but the number itself can be entered in any format that is
|
88 |
+
understood by Python; the base of the number can also be
|
89 |
+
given if it is different than 10:
|
90 |
+
|
91 |
+
>>> n = 0xFA; n
|
92 |
+
250
|
93 |
+
>>> count_digits(_)
|
94 |
+
{0: 1, 2: 1, 5: 1}
|
95 |
+
>>> count_digits(n, 16)
|
96 |
+
{10: 1, 15: 1}
|
97 |
+
|
98 |
+
The default dictionary will return a 0 for any digit that did
|
99 |
+
not appear in the number. For example, which digits appear 7
|
100 |
+
times in ``77!``:
|
101 |
+
|
102 |
+
>>> from sympy import factorial
|
103 |
+
>>> c77 = count_digits(factorial(77))
|
104 |
+
>>> [i for i in range(10) if c77[i] == 7]
|
105 |
+
[1, 3, 7, 9]
|
106 |
+
"""
|
107 |
+
rv = defaultdict(int, multiset(digits(n, b)).items())
|
108 |
+
rv.pop(b) if b in rv else rv.pop(-b) # b or -b is there
|
109 |
+
return rv
|
110 |
+
|
111 |
+
|
112 |
+
def is_palindromic(n, b=10):
|
113 |
+
"""return True if ``n`` is the same when read from left to right
|
114 |
+
or right to left in the given base, ``b``.
|
115 |
+
|
116 |
+
Examples
|
117 |
+
========
|
118 |
+
|
119 |
+
>>> from sympy.ntheory import is_palindromic
|
120 |
+
|
121 |
+
>>> all(is_palindromic(i) for i in (-11, 1, 22, 121))
|
122 |
+
True
|
123 |
+
|
124 |
+
The second argument allows you to test numbers in other
|
125 |
+
bases. For example, 88 is palindromic in base-10 but not
|
126 |
+
in base-8:
|
127 |
+
|
128 |
+
>>> is_palindromic(88, 8)
|
129 |
+
False
|
130 |
+
|
131 |
+
On the other hand, a number can be palindromic in base-8 but
|
132 |
+
not in base-10:
|
133 |
+
|
134 |
+
>>> 0o121, is_palindromic(0o121)
|
135 |
+
(81, False)
|
136 |
+
|
137 |
+
Or it might be palindromic in both bases:
|
138 |
+
|
139 |
+
>>> oct(121), is_palindromic(121, 8) and is_palindromic(121)
|
140 |
+
('0o171', True)
|
141 |
+
|
142 |
+
"""
|
143 |
+
return _palindromic(digits(n, b), 1)
|
venv/lib/python3.10/site-packages/sympy/ntheory/ecm.py
ADDED
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ympy.core.power import integer_log
|
4 |
+
from sympy.utilities.misc import as_int
|
5 |
+
import random
|
6 |
+
|
7 |
+
rgen = random.Random()
|
8 |
+
|
9 |
+
#----------------------------------------------------------------------------#
|
10 |
+
# #
|
11 |
+
# Lenstra's Elliptic Curve Factorization #
|
12 |
+
# #
|
13 |
+
#----------------------------------------------------------------------------#
|
14 |
+
|
15 |
+
|
16 |
+
class Point:
|
17 |
+
"""Montgomery form of Points in an elliptic curve.
|
18 |
+
In this form, the addition and doubling of points
|
19 |
+
does not need any y-coordinate information thus
|
20 |
+
decreasing the number of operations.
|
21 |
+
Using Montgomery form we try to perform point addition
|
22 |
+
and doubling in least amount of multiplications.
|
23 |
+
|
24 |
+
The elliptic curve used here is of the form
|
25 |
+
(E : b*y**2*z = x**3 + a*x**2*z + x*z**2).
|
26 |
+
The a_24 parameter is equal to (a + 2)/4.
|
27 |
+
|
28 |
+
References
|
29 |
+
==========
|
30 |
+
|
31 |
+
.. [1] https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
|
32 |
+
"""
|
33 |
+
|
34 |
+
def __init__(self, x_cord, z_cord, a_24, mod):
|
35 |
+
"""
|
36 |
+
Initial parameters for the Point class.
|
37 |
+
|
38 |
+
Parameters
|
39 |
+
==========
|
40 |
+
|
41 |
+
x_cord : X coordinate of the Point
|
42 |
+
z_cord : Z coordinate of the Point
|
43 |
+
a_24 : Parameter of the elliptic curve in Montgomery form
|
44 |
+
mod : modulus
|
45 |
+
"""
|
46 |
+
self.x_cord = x_cord
|
47 |
+
self.z_cord = z_cord
|
48 |
+
self.a_24 = a_24
|
49 |
+
self.mod = mod
|
50 |
+
|
51 |
+
def __eq__(self, other):
|
52 |
+
"""Two points are equal if X/Z of both points are equal
|
53 |
+
"""
|
54 |
+
if self.a_24 != other.a_24 or self.mod != other.mod:
|
55 |
+
return False
|
56 |
+
return self.x_cord * other.z_cord % self.mod ==\
|
57 |
+
other.x_cord * self.z_cord % self.mod
|
58 |
+
|
59 |
+
def add(self, Q, diff):
|
60 |
+
"""
|
61 |
+
Add two points self and Q where diff = self - Q. Moreover the assumption
|
62 |
+
is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm
|
63 |
+
requires 6 multiplications. Here the difference between the points
|
64 |
+
is already known and using this algorithm speeds up the addition
|
65 |
+
by reducing the number of multiplication required. Also in the
|
66 |
+
mont_ladder algorithm is constructed in a way so that the difference
|
67 |
+
between intermediate points is always equal to the initial point.
|
68 |
+
So, we always know what the difference between the point is.
|
69 |
+
|
70 |
+
|
71 |
+
Parameters
|
72 |
+
==========
|
73 |
+
|
74 |
+
Q : point on the curve in Montgomery form
|
75 |
+
diff : self - Q
|
76 |
+
|
77 |
+
Examples
|
78 |
+
========
|
79 |
+
|
80 |
+
>>> from sympy.ntheory.ecm import Point
|
81 |
+
>>> p1 = Point(11, 16, 7, 29)
|
82 |
+
>>> p2 = Point(13, 10, 7, 29)
|
83 |
+
>>> p3 = p2.add(p1, p1)
|
84 |
+
>>> p3.x_cord
|
85 |
+
23
|
86 |
+
>>> p3.z_cord
|
87 |
+
17
|
88 |
+
"""
|
89 |
+
u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord)
|
90 |
+
v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord)
|
91 |
+
add, subt = u + v, u - v
|
92 |
+
x_cord = diff.z_cord * add * add % self.mod
|
93 |
+
z_cord = diff.x_cord * subt * subt % self.mod
|
94 |
+
return Point(x_cord, z_cord, self.a_24, self.mod)
|
95 |
+
|
96 |
+
def double(self):
|
97 |
+
"""
|
98 |
+
Doubles a point in an elliptic curve in Montgomery form.
|
99 |
+
This algorithm requires 5 multiplications.
|
100 |
+
|
101 |
+
Examples
|
102 |
+
========
|
103 |
+
|
104 |
+
>>> from sympy.ntheory.ecm import Point
|
105 |
+
>>> p1 = Point(11, 16, 7, 29)
|
106 |
+
>>> p2 = p1.double()
|
107 |
+
>>> p2.x_cord
|
108 |
+
13
|
109 |
+
>>> p2.z_cord
|
110 |
+
10
|
111 |
+
"""
|
112 |
+
u = pow(self.x_cord + self.z_cord, 2, self.mod)
|
113 |
+
v = pow(self.x_cord - self.z_cord, 2, self.mod)
|
114 |
+
diff = u - v
|
115 |
+
x_cord = u*v % self.mod
|
116 |
+
z_cord = diff*(v + self.a_24*diff) % self.mod
|
117 |
+
return Point(x_cord, z_cord, self.a_24, self.mod)
|
118 |
+
|
119 |
+
def mont_ladder(self, k):
|
120 |
+
"""
|
121 |
+
Scalar multiplication of a point in Montgomery form
|
122 |
+
using Montgomery Ladder Algorithm.
|
123 |
+
A total of 11 multiplications are required in each step of this
|
124 |
+
algorithm.
|
125 |
+
|
126 |
+
Parameters
|
127 |
+
==========
|
128 |
+
|
129 |
+
k : The positive integer multiplier
|
130 |
+
|
131 |
+
Examples
|
132 |
+
========
|
133 |
+
|
134 |
+
>>> from sympy.ntheory.ecm import Point
|
135 |
+
>>> p1 = Point(11, 16, 7, 29)
|
136 |
+
>>> p3 = p1.mont_ladder(3)
|
137 |
+
>>> p3.x_cord
|
138 |
+
23
|
139 |
+
>>> p3.z_cord
|
140 |
+
17
|
141 |
+
"""
|
142 |
+
Q = self
|
143 |
+
R = self.double()
|
144 |
+
for i in bin(k)[3:]:
|
145 |
+
if i == '1':
|
146 |
+
Q = R.add(Q, self)
|
147 |
+
R = R.double()
|
148 |
+
else:
|
149 |
+
R = Q.add(R, self)
|
150 |
+
Q = Q.double()
|
151 |
+
return Q
|
152 |
+
|
153 |
+
|
154 |
+
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200):
|
155 |
+
"""Returns one factor of n using
|
156 |
+
Lenstra's 2 Stage Elliptic curve Factorization
|
157 |
+
with Suyama's Parameterization. Here Montgomery
|
158 |
+
arithmetic is used for fast computation of addition
|
159 |
+
and doubling of points in elliptic curve.
|
160 |
+
|
161 |
+
This ECM method considers elliptic curves in Montgomery
|
162 |
+
form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves
|
163 |
+
elliptic curve operations (mod N), where the elements in
|
164 |
+
Z are reduced (mod N). Since N is not a prime, E over FF(N)
|
165 |
+
is not really an elliptic curve but we can still do point additions
|
166 |
+
and doubling as if FF(N) was a field.
|
167 |
+
|
168 |
+
Stage 1 : The basic algorithm involves taking a random point (P) on an
|
169 |
+
elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm.
|
170 |
+
Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|,
|
171 |
+
might be a smooth number that divides k. Then we have k = l * |E(FF(q))|
|
172 |
+
for some l. For any point belonging to the curve E, |E(FF(q))|*P = O,
|
173 |
+
hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn
|
174 |
+
factor of N (q) can be recovered by taking gcd(kP.z_cord, N).
|
175 |
+
|
176 |
+
Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize
|
177 |
+
the fact that even if kP != 0, the value of k might miss just one large
|
178 |
+
prime divisor of |E(FF(q))|. In this case we only need to compute the
|
179 |
+
scalar multiplication by p to get p*k*P = O. Here a second bound B2
|
180 |
+
restrict the size of possible values of p.
|
181 |
+
|
182 |
+
Parameters
|
183 |
+
==========
|
184 |
+
|
185 |
+
n : Number to be Factored
|
186 |
+
B1 : Stage 1 Bound
|
187 |
+
B2 : Stage 2 Bound
|
188 |
+
max_curve : Maximum number of curves generated
|
189 |
+
|
190 |
+
References
|
191 |
+
==========
|
192 |
+
|
193 |
+
.. [1] Carl Pomerance and Richard Crandall "Prime Numbers:
|
194 |
+
A Computational Perspective" (2nd Ed.), page 344
|
195 |
+
"""
|
196 |
+
n = as_int(n)
|
197 |
+
if B1 % 2 != 0 or B2 % 2 != 0:
|
198 |
+
raise ValueError("The Bounds should be an even integer")
|
199 |
+
sieve.extend(B2)
|
200 |
+
|
201 |
+
if isprime(n):
|
202 |
+
return n
|
203 |
+
|
204 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
205 |
+
from sympy.polys.polytools import gcd
|
206 |
+
D = int(sqrt(B2))
|
207 |
+
beta = [0]*(D + 1)
|
208 |
+
S = [0]*(D + 1)
|
209 |
+
k = 1
|
210 |
+
for p in sieve.primerange(1, B1 + 1):
|
211 |
+
k *= pow(p, integer_log(B1, p)[0])
|
212 |
+
for _ in range(max_curve):
|
213 |
+
#Suyama's Parametrization
|
214 |
+
sigma = rgen.randint(6, n - 1)
|
215 |
+
u = (sigma*sigma - 5) % n
|
216 |
+
v = (4*sigma) % n
|
217 |
+
u_3 = pow(u, 3, n)
|
218 |
+
|
219 |
+
try:
|
220 |
+
# We use the elliptic curve y**2 = x**3 + a*x**2 + x
|
221 |
+
# where a = pow(v - u, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2
|
222 |
+
# However, we do not declare a because it is more convenient
|
223 |
+
# to use a24 = (a + 2)*mod_inverse(4, n) in the calculation.
|
224 |
+
a24 = pow(v - u, 3, n)*(3*u + v)*mod_inverse(16*u_3*v, n) % n
|
225 |
+
except ValueError:
|
226 |
+
#If the mod_inverse(16*u_3*v, n) doesn't exist (i.e., g != 1)
|
227 |
+
g = gcd(16*u_3*v, n)
|
228 |
+
#If g = n, try another curve
|
229 |
+
if g == n:
|
230 |
+
continue
|
231 |
+
return g
|
232 |
+
|
233 |
+
Q = Point(u_3, pow(v, 3, n), a24, n)
|
234 |
+
Q = Q.mont_ladder(k)
|
235 |
+
g = gcd(Q.z_cord, n)
|
236 |
+
|
237 |
+
#Stage 1 factor
|
238 |
+
if g != 1 and g != n:
|
239 |
+
return g
|
240 |
+
#Stage 1 failure. Q.z = 0, Try another curve
|
241 |
+
elif g == n:
|
242 |
+
continue
|
243 |
+
|
244 |
+
#Stage 2 - Improved Standard Continuation
|
245 |
+
S[1] = Q.double()
|
246 |
+
S[2] = S[1].double()
|
247 |
+
beta[1] = (S[1].x_cord*S[1].z_cord) % n
|
248 |
+
beta[2] = (S[2].x_cord*S[2].z_cord) % n
|
249 |
+
|
250 |
+
for d in range(3, D + 1):
|
251 |
+
S[d] = S[d - 1].add(S[1], S[d - 2])
|
252 |
+
beta[d] = (S[d].x_cord*S[d].z_cord) % n
|
253 |
+
|
254 |
+
g = 1
|
255 |
+
B = B1 - 1
|
256 |
+
T = Q.mont_ladder(B - 2*D)
|
257 |
+
R = Q.mont_ladder(B)
|
258 |
+
|
259 |
+
for r in range(B, B2, 2*D):
|
260 |
+
alpha = (R.x_cord*R.z_cord) % n
|
261 |
+
for q in sieve.primerange(r + 2, r + 2*D + 1):
|
262 |
+
delta = (q - r) // 2
|
263 |
+
# We want to calculate
|
264 |
+
# f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord
|
265 |
+
f = (R.x_cord - S[delta].x_cord)*\
|
266 |
+
(R.z_cord + S[delta].z_cord) - alpha + beta[delta]
|
267 |
+
g = (g*f) % n
|
268 |
+
#Swap
|
269 |
+
T, R = R, R.add(S[D], T)
|
270 |
+
g = gcd(n, g)
|
271 |
+
|
272 |
+
#Stage 2 Factor found
|
273 |
+
if g != 1 and g != n:
|
274 |
+
return g
|
275 |
+
|
276 |
+
#ECM failed, Increase the bounds
|
277 |
+
raise ValueError("Increase the bounds")
|
278 |
+
|
279 |
+
|
280 |
+
def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234):
|
281 |
+
"""Performs factorization using Lenstra's Elliptic curve method.
|
282 |
+
|
283 |
+
This function repeatedly calls `ecm_one_factor` to compute the factors
|
284 |
+
of n. First all the small factors are taken out using trial division.
|
285 |
+
Then `ecm_one_factor` is used to compute one factor at a time.
|
286 |
+
|
287 |
+
Parameters
|
288 |
+
==========
|
289 |
+
|
290 |
+
n : Number to be Factored
|
291 |
+
B1 : Stage 1 Bound
|
292 |
+
B2 : Stage 2 Bound
|
293 |
+
max_curve : Maximum number of curves generated
|
294 |
+
seed : Initialize pseudorandom generator
|
295 |
+
|
296 |
+
Examples
|
297 |
+
========
|
298 |
+
|
299 |
+
>>> from sympy.ntheory import ecm
|
300 |
+
>>> ecm(25645121643901801)
|
301 |
+
{5394769, 4753701529}
|
302 |
+
>>> ecm(9804659461513846513)
|
303 |
+
{4641991, 2112166839943}
|
304 |
+
"""
|
305 |
+
_factors = set()
|
306 |
+
for prime in sieve.primerange(1, 100000):
|
307 |
+
if n % prime == 0:
|
308 |
+
_factors.add(prime)
|
309 |
+
while(n % prime == 0):
|
310 |
+
n //= prime
|
311 |
+
rgen.seed(seed)
|
312 |
+
while(n > 1):
|
313 |
+
try:
|
314 |
+
factor = _ecm_one_factor(n, B1, B2, max_curve)
|
315 |
+
except ValueError:
|
316 |
+
raise ValueError("Increase the bounds")
|
317 |
+
_factors.add(factor)
|
318 |
+
n //= factor
|
319 |
+
|
320 |
+
factors = set()
|
321 |
+
for factor in _factors:
|
322 |
+
if isprime(factor):
|
323 |
+
factors.add(factor)
|
324 |
+
continue
|
325 |
+
factors |= ecm(factor)
|
326 |
+
return factors
|
venv/lib/python3.10/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.10/site-packages/sympy/ntheory/elliptic_curve.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import oo
|
2 |
+
from sympy.core.relational import Eq
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.polys.domains import FiniteField, QQ, RationalField, FF
|
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 |
+
|
13 |
+
class EllipticCurve:
|
14 |
+
"""
|
15 |
+
Create the following Elliptic Curve over domain.
|
16 |
+
|
17 |
+
`y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}`
|
18 |
+
|
19 |
+
The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``,
|
20 |
+
it create curve as following form.
|
21 |
+
|
22 |
+
`y^{2} = x^{3} + a_{4} x + a_{6}`
|
23 |
+
|
24 |
+
Examples
|
25 |
+
========
|
26 |
+
|
27 |
+
References
|
28 |
+
==========
|
29 |
+
|
30 |
+
.. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition
|
31 |
+
.. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html
|
32 |
+
.. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition
|
33 |
+
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus = 0):
|
37 |
+
if modulus == 0:
|
38 |
+
domain = QQ
|
39 |
+
else:
|
40 |
+
domain = FF(modulus)
|
41 |
+
a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6))
|
42 |
+
self._domain = domain
|
43 |
+
self.modulus = modulus
|
44 |
+
# Calculate discriminant
|
45 |
+
b2 = a1**2 + 4 * a2
|
46 |
+
b4 = 2 * a4 + a1 * a3
|
47 |
+
b6 = a3**2 + 4 * a6
|
48 |
+
b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2
|
49 |
+
self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8
|
50 |
+
self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6
|
51 |
+
self._a1 = a1
|
52 |
+
self._a2 = a2
|
53 |
+
self._a3 = a3
|
54 |
+
self._a4 = a4
|
55 |
+
self._a6 = a6
|
56 |
+
x, y, z = symbols('x y z')
|
57 |
+
self.x, self.y, self.z = x, y, z
|
58 |
+
self._eq = Eq(y**2*z + a1*x*y*z + a3*y*z**2, x**3 + a2*x**2*z + a4*x*z**2 + a6*z**3)
|
59 |
+
if isinstance(self._domain, FiniteField):
|
60 |
+
self._rank = 0
|
61 |
+
elif isinstance(self._domain, RationalField):
|
62 |
+
self._rank = None
|
63 |
+
|
64 |
+
def __call__(self, x, y, z=1):
|
65 |
+
return EllipticCurvePoint(x, y, z, self)
|
66 |
+
|
67 |
+
def __contains__(self, point):
|
68 |
+
if is_sequence(point):
|
69 |
+
if len(point) == 2:
|
70 |
+
z1 = 1
|
71 |
+
else:
|
72 |
+
z1 = point[2]
|
73 |
+
x1, y1 = point[:2]
|
74 |
+
elif isinstance(point, EllipticCurvePoint):
|
75 |
+
x1, y1, z1 = point.x, point.y, point.z
|
76 |
+
else:
|
77 |
+
raise ValueError('Invalid point.')
|
78 |
+
if self.characteristic == 0 and z1 == 0:
|
79 |
+
return True
|
80 |
+
return self._eq.subs({self.x: x1, self.y: y1, self.z: z1})
|
81 |
+
|
82 |
+
def __repr__(self):
|
83 |
+
return 'E({}): {}'.format(self._domain, self._eq)
|
84 |
+
|
85 |
+
def minimal(self):
|
86 |
+
"""
|
87 |
+
Return minimal Weierstrass equation.
|
88 |
+
|
89 |
+
Examples
|
90 |
+
========
|
91 |
+
|
92 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
93 |
+
|
94 |
+
>>> e1 = EllipticCurve(-10, -20, 0, -1, 1)
|
95 |
+
>>> e1.minimal()
|
96 |
+
E(QQ): Eq(y**2*z, x**3 - 13392*x*z**2 - 1080432*z**3)
|
97 |
+
|
98 |
+
"""
|
99 |
+
char = self.characteristic
|
100 |
+
if char == 2:
|
101 |
+
return self
|
102 |
+
if char == 3:
|
103 |
+
return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus)
|
104 |
+
c4 = self._b2**2 - 24*self._b4
|
105 |
+
c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6
|
106 |
+
return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus)
|
107 |
+
|
108 |
+
def points(self):
|
109 |
+
"""
|
110 |
+
Return points of curve over Finite Field.
|
111 |
+
|
112 |
+
Examples
|
113 |
+
========
|
114 |
+
|
115 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
116 |
+
>>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5)
|
117 |
+
>>> e2.points()
|
118 |
+
{(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)}
|
119 |
+
|
120 |
+
"""
|
121 |
+
|
122 |
+
char = self.characteristic
|
123 |
+
all_pt = set()
|
124 |
+
if char >= 1:
|
125 |
+
for i in range(char):
|
126 |
+
congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: i, self.z: 1}))
|
127 |
+
sol = polynomial_congruence(congruence_eq, char)
|
128 |
+
for num in sol:
|
129 |
+
all_pt.add((i, num))
|
130 |
+
return all_pt
|
131 |
+
else:
|
132 |
+
raise ValueError("Infinitely many points")
|
133 |
+
|
134 |
+
def points_x(self, x):
|
135 |
+
"Returns points on with curve where xcoordinate = x"
|
136 |
+
pt = []
|
137 |
+
if self._domain == QQ:
|
138 |
+
for y in solve(self._eq.subs(self.x, x)):
|
139 |
+
pt.append((x, y))
|
140 |
+
congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: x, self.z: 1}))
|
141 |
+
for y in polynomial_congruence(congruence_eq, self.characteristic):
|
142 |
+
pt.append((x, y))
|
143 |
+
return pt
|
144 |
+
|
145 |
+
def torsion_points(self):
|
146 |
+
"""
|
147 |
+
Return torsion points of curve over Rational number.
|
148 |
+
|
149 |
+
Return point objects those are finite order.
|
150 |
+
According to Nagell-Lutz theorem, torsion point p(x, y)
|
151 |
+
x and y are integers, either y = 0 or y**2 is divisor
|
152 |
+
of discriminent. According to Mazur's theorem, there are
|
153 |
+
at most 15 points in torsion collection.
|
154 |
+
|
155 |
+
Examples
|
156 |
+
========
|
157 |
+
|
158 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
159 |
+
>>> e2 = EllipticCurve(-43, 166)
|
160 |
+
>>> sorted(e2.torsion_points())
|
161 |
+
[(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)]
|
162 |
+
|
163 |
+
"""
|
164 |
+
if self.characteristic > 0:
|
165 |
+
raise ValueError("No torsion point for Finite Field.")
|
166 |
+
l = [EllipticCurvePoint.point_at_infinity(self)]
|
167 |
+
for xx in solve(self._eq.subs({self.y: 0, self.z: 1})):
|
168 |
+
if xx.is_rational:
|
169 |
+
l.append(self(xx, 0))
|
170 |
+
for i in divisors(self.discriminant, generator=True):
|
171 |
+
j = int(i**.5)
|
172 |
+
if j**2 == i:
|
173 |
+
for xx in solve(self._eq.subs({self.y: j, self.z: 1})):
|
174 |
+
if not xx.is_rational:
|
175 |
+
continue
|
176 |
+
p = self(xx, j)
|
177 |
+
if p.order() != oo:
|
178 |
+
l.extend([p, -p])
|
179 |
+
return l
|
180 |
+
|
181 |
+
@property
|
182 |
+
def characteristic(self):
|
183 |
+
"""
|
184 |
+
Return domain characteristic.
|
185 |
+
|
186 |
+
Examples
|
187 |
+
========
|
188 |
+
|
189 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
190 |
+
>>> e2 = EllipticCurve(-43, 166)
|
191 |
+
>>> e2.characteristic
|
192 |
+
0
|
193 |
+
|
194 |
+
"""
|
195 |
+
return self._domain.characteristic()
|
196 |
+
|
197 |
+
@property
|
198 |
+
def discriminant(self):
|
199 |
+
"""
|
200 |
+
Return curve discriminant.
|
201 |
+
|
202 |
+
Examples
|
203 |
+
========
|
204 |
+
|
205 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
206 |
+
>>> e2 = EllipticCurve(0, 17)
|
207 |
+
>>> e2.discriminant
|
208 |
+
-124848
|
209 |
+
|
210 |
+
"""
|
211 |
+
return int(self._discrim)
|
212 |
+
|
213 |
+
@property
|
214 |
+
def is_singular(self):
|
215 |
+
"""
|
216 |
+
Return True if curve discriminant is equal to zero.
|
217 |
+
"""
|
218 |
+
return self.discriminant == 0
|
219 |
+
|
220 |
+
@property
|
221 |
+
def j_invariant(self):
|
222 |
+
"""
|
223 |
+
Return curve j-invariant.
|
224 |
+
|
225 |
+
Examples
|
226 |
+
========
|
227 |
+
|
228 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
229 |
+
>>> e1 = EllipticCurve(-2, 0, 0, 1, 1)
|
230 |
+
>>> e1.j_invariant
|
231 |
+
1404928/389
|
232 |
+
|
233 |
+
"""
|
234 |
+
c4 = self._b2**2 - 24*self._b4
|
235 |
+
return self._domain.to_sympy(c4**3 / self._discrim)
|
236 |
+
|
237 |
+
@property
|
238 |
+
def order(self):
|
239 |
+
"""
|
240 |
+
Number of points in Finite field.
|
241 |
+
|
242 |
+
Examples
|
243 |
+
========
|
244 |
+
|
245 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
246 |
+
>>> e2 = EllipticCurve(1, 0, modulus=19)
|
247 |
+
>>> e2.order
|
248 |
+
19
|
249 |
+
|
250 |
+
"""
|
251 |
+
if self.characteristic == 0:
|
252 |
+
raise NotImplementedError("Still not implemented")
|
253 |
+
return len(self.points())
|
254 |
+
|
255 |
+
@property
|
256 |
+
def rank(self):
|
257 |
+
"""
|
258 |
+
Number of independent points of infinite order.
|
259 |
+
|
260 |
+
For Finite field, it must be 0.
|
261 |
+
"""
|
262 |
+
if self._rank is not None:
|
263 |
+
return self._rank
|
264 |
+
raise NotImplementedError("Still not implemented")
|
265 |
+
|
266 |
+
|
267 |
+
class EllipticCurvePoint:
|
268 |
+
"""
|
269 |
+
Point of Elliptic Curve
|
270 |
+
|
271 |
+
Examples
|
272 |
+
========
|
273 |
+
|
274 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
275 |
+
>>> e1 = EllipticCurve(-17, 16)
|
276 |
+
>>> p1 = e1(0, -4, 1)
|
277 |
+
>>> p2 = e1(1, 0)
|
278 |
+
>>> p1 + p2
|
279 |
+
(15, -56)
|
280 |
+
>>> e3 = EllipticCurve(-1, 9)
|
281 |
+
>>> e3(1, -3) * 3
|
282 |
+
(664/169, 17811/2197)
|
283 |
+
>>> (e3(1, -3) * 3).order()
|
284 |
+
oo
|
285 |
+
>>> e2 = EllipticCurve(-2, 0, 0, 1, 1)
|
286 |
+
>>> p = e2(-1,1)
|
287 |
+
>>> q = e2(0, -1)
|
288 |
+
>>> p+q
|
289 |
+
(4, 8)
|
290 |
+
>>> p-q
|
291 |
+
(1, 0)
|
292 |
+
>>> 3*p-5*q
|
293 |
+
(328/361, -2800/6859)
|
294 |
+
"""
|
295 |
+
|
296 |
+
@staticmethod
|
297 |
+
def point_at_infinity(curve):
|
298 |
+
return EllipticCurvePoint(0, 1, 0, curve)
|
299 |
+
|
300 |
+
def __init__(self, x, y, z, curve):
|
301 |
+
dom = curve._domain.convert
|
302 |
+
self.x = dom(x)
|
303 |
+
self.y = dom(y)
|
304 |
+
self.z = dom(z)
|
305 |
+
self._curve = curve
|
306 |
+
self._domain = self._curve._domain
|
307 |
+
if not self._curve.__contains__(self):
|
308 |
+
raise ValueError("The curve does not contain this point")
|
309 |
+
|
310 |
+
def __add__(self, p):
|
311 |
+
if self.z == 0:
|
312 |
+
return p
|
313 |
+
if p.z == 0:
|
314 |
+
return self
|
315 |
+
x1, y1 = self.x/self.z, self.y/self.z
|
316 |
+
x2, y2 = p.x/p.z, p.y/p.z
|
317 |
+
a1 = self._curve._a1
|
318 |
+
a2 = self._curve._a2
|
319 |
+
a3 = self._curve._a3
|
320 |
+
a4 = self._curve._a4
|
321 |
+
a6 = self._curve._a6
|
322 |
+
if x1 != x2:
|
323 |
+
slope = (y1 - y2) / (x1 - x2)
|
324 |
+
yint = (y1 * x2 - y2 * x1) / (x2 - x1)
|
325 |
+
else:
|
326 |
+
if (y1 + y2) == 0:
|
327 |
+
return self.point_at_infinity(self._curve)
|
328 |
+
slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
|
329 |
+
yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
|
330 |
+
x3 = slope**2 + a1*slope - a2 - x1 - x2
|
331 |
+
y3 = -(slope + a1) * x3 - yint - a3
|
332 |
+
return self._curve(x3, y3, 1)
|
333 |
+
|
334 |
+
def __lt__(self, other):
|
335 |
+
return (self.x, self.y, self.z) < (other.x, other.y, other.z)
|
336 |
+
|
337 |
+
def __mul__(self, n):
|
338 |
+
n = as_int(n)
|
339 |
+
r = self.point_at_infinity(self._curve)
|
340 |
+
if n == 0:
|
341 |
+
return r
|
342 |
+
if n < 0:
|
343 |
+
return -self * -n
|
344 |
+
p = self
|
345 |
+
while n:
|
346 |
+
if n & 1:
|
347 |
+
r = r + p
|
348 |
+
n >>= 1
|
349 |
+
p = p + p
|
350 |
+
return r
|
351 |
+
|
352 |
+
def __rmul__(self, n):
|
353 |
+
return self * n
|
354 |
+
|
355 |
+
def __neg__(self):
|
356 |
+
return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)
|
357 |
+
|
358 |
+
def __repr__(self):
|
359 |
+
if self.z == 0:
|
360 |
+
return 'O'
|
361 |
+
dom = self._curve._domain
|
362 |
+
try:
|
363 |
+
return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y))
|
364 |
+
except TypeError:
|
365 |
+
pass
|
366 |
+
return '({}, {})'.format(self.x, self.y)
|
367 |
+
|
368 |
+
def __sub__(self, other):
|
369 |
+
return self.__add__(-other)
|
370 |
+
|
371 |
+
def order(self):
|
372 |
+
"""
|
373 |
+
Return point order n where nP = 0.
|
374 |
+
|
375 |
+
"""
|
376 |
+
if self.z == 0:
|
377 |
+
return 1
|
378 |
+
if self.y == 0: # P = -P
|
379 |
+
return 2
|
380 |
+
p = self * 2
|
381 |
+
if p.y == -self.y: # 2P = -P
|
382 |
+
return 3
|
383 |
+
i = 2
|
384 |
+
if self._domain != QQ:
|
385 |
+
while int(p.x) == p.x and int(p.y) == p.y:
|
386 |
+
p = self + p
|
387 |
+
i += 1
|
388 |
+
if p.z == 0:
|
389 |
+
return i
|
390 |
+
return oo
|
391 |
+
while p.x.numerator == p.x and p.y.numerator == p.y:
|
392 |
+
p = self + p
|
393 |
+
i += 1
|
394 |
+
if i > 12:
|
395 |
+
return oo
|
396 |
+
if p.z == 0:
|
397 |
+
return i
|
398 |
+
return oo
|
venv/lib/python3.10/site-packages/sympy/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Integer factorization
|
3 |
+
"""
|
4 |
+
|
5 |
+
from collections import defaultdict
|
6 |
+
from functools import reduce
|
7 |
+
import random
|
8 |
+
import math
|
9 |
+
|
10 |
+
from sympy.core import sympify
|
11 |
+
from sympy.core.containers import Dict
|
12 |
+
from sympy.core.evalf import bitcount
|
13 |
+
from sympy.core.expr import Expr
|
14 |
+
from sympy.core.function import Function
|
15 |
+
from sympy.core.logic import fuzzy_and
|
16 |
+
from sympy.core.mul import Mul
|
17 |
+
from sympy.core.numbers import igcd, ilcm, Rational, Integer
|
18 |
+
from sympy.core.power import integer_nthroot, Pow, integer_log
|
19 |
+
from sympy.core.singleton import S
|
20 |
+
from sympy.external.gmpy import SYMPY_INTS
|
21 |
+
from .primetest import isprime
|
22 |
+
from .generate import sieve, primerange, nextprime
|
23 |
+
from .digits import digits
|
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 |
+
# Note: This list should be updated whenever new Mersenne primes are found.
|
29 |
+
# Refer: https://www.mersenne.org/
|
30 |
+
MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
|
31 |
+
2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
|
32 |
+
216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
|
33 |
+
25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933)
|
34 |
+
|
35 |
+
# compute more when needed for i in Mersenne prime exponents
|
36 |
+
PERFECT = [6] # 2**(i-1)*(2**i-1)
|
37 |
+
MERSENNES = [3] # 2**i - 1
|
38 |
+
|
39 |
+
|
40 |
+
def _ismersenneprime(n):
|
41 |
+
global MERSENNES
|
42 |
+
j = len(MERSENNES)
|
43 |
+
while n > MERSENNES[-1] and j < len(MERSENNE_PRIME_EXPONENTS):
|
44 |
+
# conservatively grow the list
|
45 |
+
MERSENNES.append(2**MERSENNE_PRIME_EXPONENTS[j] - 1)
|
46 |
+
j += 1
|
47 |
+
return n in MERSENNES
|
48 |
+
|
49 |
+
|
50 |
+
def _isperfect(n):
|
51 |
+
global PERFECT
|
52 |
+
if n % 2 == 0:
|
53 |
+
j = len(PERFECT)
|
54 |
+
while n > PERFECT[-1] and j < len(MERSENNE_PRIME_EXPONENTS):
|
55 |
+
# conservatively grow the list
|
56 |
+
t = 2**(MERSENNE_PRIME_EXPONENTS[j] - 1)
|
57 |
+
PERFECT.append(t*(2*t - 1))
|
58 |
+
j += 1
|
59 |
+
return n in PERFECT
|
60 |
+
|
61 |
+
|
62 |
+
small_trailing = [0] * 256
|
63 |
+
for j in range(1,8):
|
64 |
+
small_trailing[1<<j::1<<(j+1)] = [j] * (1<<(7-j))
|
65 |
+
|
66 |
+
|
67 |
+
def smoothness(n):
|
68 |
+
"""
|
69 |
+
Return the B-smooth and B-power smooth values of n.
|
70 |
+
|
71 |
+
The smoothness of n is the largest prime factor of n; the power-
|
72 |
+
smoothness is the largest divisor raised to its multiplicity.
|
73 |
+
|
74 |
+
Examples
|
75 |
+
========
|
76 |
+
|
77 |
+
>>> from sympy.ntheory.factor_ import smoothness
|
78 |
+
>>> smoothness(2**7*3**2)
|
79 |
+
(3, 128)
|
80 |
+
>>> smoothness(2**4*13)
|
81 |
+
(13, 16)
|
82 |
+
>>> smoothness(2)
|
83 |
+
(2, 2)
|
84 |
+
|
85 |
+
See Also
|
86 |
+
========
|
87 |
+
|
88 |
+
factorint, smoothness_p
|
89 |
+
"""
|
90 |
+
|
91 |
+
if n == 1:
|
92 |
+
return (1, 1) # not prime, but otherwise this causes headaches
|
93 |
+
facs = factorint(n)
|
94 |
+
return max(facs), max(m**facs[m] for m in facs)
|
95 |
+
|
96 |
+
|
97 |
+
def smoothness_p(n, m=-1, power=0, visual=None):
|
98 |
+
"""
|
99 |
+
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
|
100 |
+
where:
|
101 |
+
|
102 |
+
1. p**M is the base-p divisor of n
|
103 |
+
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
|
104 |
+
3. psm(p + m) is the power smoothness of p + m
|
105 |
+
|
106 |
+
The list is sorted according to smoothness (default) or by power smoothness
|
107 |
+
if power=1.
|
108 |
+
|
109 |
+
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
|
110 |
+
factor govern the results that are obtained from the p +/- 1 type factoring
|
111 |
+
methods.
|
112 |
+
|
113 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
|
114 |
+
>>> smoothness_p(10431, m=1)
|
115 |
+
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
|
116 |
+
>>> smoothness_p(10431)
|
117 |
+
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
|
118 |
+
>>> smoothness_p(10431, power=1)
|
119 |
+
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
|
120 |
+
|
121 |
+
If visual=True then an annotated string will be returned:
|
122 |
+
|
123 |
+
>>> print(smoothness_p(21477639576571, visual=1))
|
124 |
+
p**i=4410317**1 has p-1 B=1787, B-pow=1787
|
125 |
+
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
|
126 |
+
|
127 |
+
This string can also be generated directly from a factorization dictionary
|
128 |
+
and vice versa:
|
129 |
+
|
130 |
+
>>> factorint(17*9)
|
131 |
+
{3: 2, 17: 1}
|
132 |
+
>>> smoothness_p(_)
|
133 |
+
'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
|
134 |
+
>>> smoothness_p(_)
|
135 |
+
{3: 2, 17: 1}
|
136 |
+
|
137 |
+
The table of the output logic is:
|
138 |
+
|
139 |
+
====== ====== ======= =======
|
140 |
+
| Visual
|
141 |
+
------ ----------------------
|
142 |
+
Input True False other
|
143 |
+
====== ====== ======= =======
|
144 |
+
dict str tuple str
|
145 |
+
str str tuple dict
|
146 |
+
tuple str tuple str
|
147 |
+
n str tuple tuple
|
148 |
+
mul str tuple tuple
|
149 |
+
====== ====== ======= =======
|
150 |
+
|
151 |
+
See Also
|
152 |
+
========
|
153 |
+
|
154 |
+
factorint, smoothness
|
155 |
+
"""
|
156 |
+
|
157 |
+
# visual must be True, False or other (stored as None)
|
158 |
+
if visual in (1, 0):
|
159 |
+
visual = bool(visual)
|
160 |
+
elif visual not in (True, False):
|
161 |
+
visual = None
|
162 |
+
|
163 |
+
if isinstance(n, str):
|
164 |
+
if visual:
|
165 |
+
return n
|
166 |
+
d = {}
|
167 |
+
for li in n.splitlines():
|
168 |
+
k, v = [int(i) for i in
|
169 |
+
li.split('has')[0].split('=')[1].split('**')]
|
170 |
+
d[k] = v
|
171 |
+
if visual is not True and visual is not False:
|
172 |
+
return d
|
173 |
+
return smoothness_p(d, visual=False)
|
174 |
+
elif not isinstance(n, tuple):
|
175 |
+
facs = factorint(n, visual=False)
|
176 |
+
|
177 |
+
if power:
|
178 |
+
k = -1
|
179 |
+
else:
|
180 |
+
k = 1
|
181 |
+
if isinstance(n, tuple):
|
182 |
+
rv = n
|
183 |
+
else:
|
184 |
+
rv = (m, sorted([(f,
|
185 |
+
tuple([M] + list(smoothness(f + m))))
|
186 |
+
for f, M in list(facs.items())],
|
187 |
+
key=lambda x: (x[1][k], x[0])))
|
188 |
+
|
189 |
+
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
|
190 |
+
return rv
|
191 |
+
lines = []
|
192 |
+
for dat in rv[1]:
|
193 |
+
dat = flatten(dat)
|
194 |
+
dat.insert(2, m)
|
195 |
+
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
|
196 |
+
return '\n'.join(lines)
|
197 |
+
|
198 |
+
|
199 |
+
def trailing(n):
|
200 |
+
"""Count the number of trailing zero digits in the binary
|
201 |
+
representation of n, i.e. determine the largest power of 2
|
202 |
+
that divides n.
|
203 |
+
|
204 |
+
Examples
|
205 |
+
========
|
206 |
+
|
207 |
+
>>> from sympy import trailing
|
208 |
+
>>> trailing(128)
|
209 |
+
7
|
210 |
+
>>> trailing(63)
|
211 |
+
0
|
212 |
+
"""
|
213 |
+
n = abs(int(n))
|
214 |
+
if not n:
|
215 |
+
return 0
|
216 |
+
low_byte = n & 0xff
|
217 |
+
if low_byte:
|
218 |
+
return small_trailing[low_byte]
|
219 |
+
|
220 |
+
# 2**m is quick for z up through 2**30
|
221 |
+
z = bitcount(n) - 1
|
222 |
+
if isinstance(z, SYMPY_INTS):
|
223 |
+
if n == 1 << z:
|
224 |
+
return z
|
225 |
+
|
226 |
+
if z < 300:
|
227 |
+
# fixed 8-byte reduction
|
228 |
+
t = 8
|
229 |
+
n >>= 8
|
230 |
+
while not n & 0xff:
|
231 |
+
n >>= 8
|
232 |
+
t += 8
|
233 |
+
return t + small_trailing[n & 0xff]
|
234 |
+
|
235 |
+
# binary reduction important when there might be a large
|
236 |
+
# number of trailing 0s
|
237 |
+
t = 0
|
238 |
+
p = 8
|
239 |
+
while not n & 1:
|
240 |
+
while not n & ((1 << p) - 1):
|
241 |
+
n >>= p
|
242 |
+
t += p
|
243 |
+
p *= 2
|
244 |
+
p //= 2
|
245 |
+
return t
|
246 |
+
|
247 |
+
|
248 |
+
def multiplicity(p, n):
|
249 |
+
"""
|
250 |
+
Find the greatest integer m such that p**m divides n.
|
251 |
+
|
252 |
+
Examples
|
253 |
+
========
|
254 |
+
|
255 |
+
>>> from sympy import multiplicity, Rational
|
256 |
+
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
|
257 |
+
[0, 1, 2, 3, 3]
|
258 |
+
>>> multiplicity(3, Rational(1, 9))
|
259 |
+
-2
|
260 |
+
|
261 |
+
Note: when checking for the multiplicity of a number in a
|
262 |
+
large factorial it is most efficient to send it as an unevaluated
|
263 |
+
factorial or to call ``multiplicity_in_factorial`` directly:
|
264 |
+
|
265 |
+
>>> from sympy.ntheory import multiplicity_in_factorial
|
266 |
+
>>> from sympy import factorial
|
267 |
+
>>> p = factorial(25)
|
268 |
+
>>> n = 2**100
|
269 |
+
>>> nfac = factorial(n, evaluate=False)
|
270 |
+
>>> multiplicity(p, nfac)
|
271 |
+
52818775009509558395695966887
|
272 |
+
>>> _ == multiplicity_in_factorial(p, n)
|
273 |
+
True
|
274 |
+
|
275 |
+
"""
|
276 |
+
try:
|
277 |
+
p, n = as_int(p), as_int(n)
|
278 |
+
except ValueError:
|
279 |
+
from sympy.functions.combinatorial.factorials import factorial
|
280 |
+
if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
|
281 |
+
p = Rational(p)
|
282 |
+
n = Rational(n)
|
283 |
+
if p.q == 1:
|
284 |
+
if n.p == 1:
|
285 |
+
return -multiplicity(p.p, n.q)
|
286 |
+
return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
|
287 |
+
elif p.p == 1:
|
288 |
+
return multiplicity(p.q, n.q)
|
289 |
+
else:
|
290 |
+
like = min(
|
291 |
+
multiplicity(p.p, n.p),
|
292 |
+
multiplicity(p.q, n.q))
|
293 |
+
cross = min(
|
294 |
+
multiplicity(p.q, n.p),
|
295 |
+
multiplicity(p.p, n.q))
|
296 |
+
return like - cross
|
297 |
+
elif (isinstance(p, (SYMPY_INTS, Integer)) and
|
298 |
+
isinstance(n, factorial) and
|
299 |
+
isinstance(n.args[0], Integer) and
|
300 |
+
n.args[0] >= 0):
|
301 |
+
return multiplicity_in_factorial(p, n.args[0])
|
302 |
+
raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
|
303 |
+
|
304 |
+
if n == 0:
|
305 |
+
raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
|
306 |
+
if p == 2:
|
307 |
+
return trailing(n)
|
308 |
+
if p < 2:
|
309 |
+
raise ValueError('p must be an integer, 2 or larger, but got %s' % p)
|
310 |
+
if p == n:
|
311 |
+
return 1
|
312 |
+
|
313 |
+
m = 0
|
314 |
+
n, rem = divmod(n, p)
|
315 |
+
while not rem:
|
316 |
+
m += 1
|
317 |
+
if m > 5:
|
318 |
+
# The multiplicity could be very large. Better
|
319 |
+
# to increment in powers of two
|
320 |
+
e = 2
|
321 |
+
while 1:
|
322 |
+
ppow = p**e
|
323 |
+
if ppow < n:
|
324 |
+
nnew, rem = divmod(n, ppow)
|
325 |
+
if not rem:
|
326 |
+
m += e
|
327 |
+
e *= 2
|
328 |
+
n = nnew
|
329 |
+
continue
|
330 |
+
return m + multiplicity(p, n)
|
331 |
+
n, rem = divmod(n, p)
|
332 |
+
return m
|
333 |
+
|
334 |
+
|
335 |
+
def multiplicity_in_factorial(p, n):
|
336 |
+
"""return the largest integer ``m`` such that ``p**m`` divides ``n!``
|
337 |
+
without calculating the factorial of ``n``.
|
338 |
+
|
339 |
+
|
340 |
+
Examples
|
341 |
+
========
|
342 |
+
|
343 |
+
>>> from sympy.ntheory import multiplicity_in_factorial
|
344 |
+
>>> from sympy import factorial
|
345 |
+
|
346 |
+
>>> multiplicity_in_factorial(2, 3)
|
347 |
+
1
|
348 |
+
|
349 |
+
An instructive use of this is to tell how many trailing zeros
|
350 |
+
a given factorial has. For example, there are 6 in 25!:
|
351 |
+
|
352 |
+
>>> factorial(25)
|
353 |
+
15511210043330985984000000
|
354 |
+
>>> multiplicity_in_factorial(10, 25)
|
355 |
+
6
|
356 |
+
|
357 |
+
For large factorials, it is much faster/feasible to use
|
358 |
+
this function rather than computing the actual factorial:
|
359 |
+
|
360 |
+
>>> multiplicity_in_factorial(factorial(25), 2**100)
|
361 |
+
52818775009509558395695966887
|
362 |
+
|
363 |
+
"""
|
364 |
+
|
365 |
+
p, n = as_int(p), as_int(n)
|
366 |
+
|
367 |
+
if p <= 0:
|
368 |
+
raise ValueError('expecting positive integer got %s' % p )
|
369 |
+
|
370 |
+
if n < 0:
|
371 |
+
raise ValueError('expecting non-negative integer got %s' % n )
|
372 |
+
|
373 |
+
factors = factorint(p)
|
374 |
+
|
375 |
+
# keep only the largest of a given multiplicity since those
|
376 |
+
# of a given multiplicity will be goverened by the behavior
|
377 |
+
# of the largest factor
|
378 |
+
test = defaultdict(int)
|
379 |
+
for k, v in factors.items():
|
380 |
+
test[v] = max(k, test[v])
|
381 |
+
keep = set(test.values())
|
382 |
+
# remove others from factors
|
383 |
+
for k in list(factors.keys()):
|
384 |
+
if k not in keep:
|
385 |
+
factors.pop(k)
|
386 |
+
|
387 |
+
mp = S.Infinity
|
388 |
+
for i in factors:
|
389 |
+
# multiplicity of i in n! is
|
390 |
+
mi = (n - (sum(digits(n, i)) - i))//(i - 1)
|
391 |
+
# multiplicity of p in n! depends on multiplicity
|
392 |
+
# of prime `i` in p, so we floor divide by factors[i]
|
393 |
+
# and keep it if smaller than the multiplicity of p
|
394 |
+
# seen so far
|
395 |
+
mp = min(mp, mi//factors[i])
|
396 |
+
|
397 |
+
return mp
|
398 |
+
|
399 |
+
|
400 |
+
def perfect_power(n, candidates=None, big=True, factor=True):
|
401 |
+
"""
|
402 |
+
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
|
403 |
+
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
|
404 |
+
perfect power). A ValueError is raised if ``n`` is not Rational.
|
405 |
+
|
406 |
+
By default, the base is recursively decomposed and the exponents
|
407 |
+
collected so the largest possible ``e`` is sought. If ``big=False``
|
408 |
+
then the smallest possible ``e`` (thus prime) will be chosen.
|
409 |
+
|
410 |
+
If ``factor=True`` then simultaneous factorization of ``n`` is
|
411 |
+
attempted since finding a factor indicates the only possible root
|
412 |
+
for ``n``. This is True by default since only a few small factors will
|
413 |
+
be tested in the course of searching for the perfect power.
|
414 |
+
|
415 |
+
The use of ``candidates`` is primarily for internal use; if provided,
|
416 |
+
False will be returned if ``n`` cannot be written as a power with one
|
417 |
+
of the candidates as an exponent and factoring (beyond testing for
|
418 |
+
a factor of 2) will not be attempted.
|
419 |
+
|
420 |
+
Examples
|
421 |
+
========
|
422 |
+
|
423 |
+
>>> from sympy import perfect_power, Rational
|
424 |
+
>>> perfect_power(16)
|
425 |
+
(2, 4)
|
426 |
+
>>> perfect_power(16, big=False)
|
427 |
+
(4, 2)
|
428 |
+
|
429 |
+
Negative numbers can only have odd perfect powers:
|
430 |
+
|
431 |
+
>>> perfect_power(-4)
|
432 |
+
False
|
433 |
+
>>> perfect_power(-8)
|
434 |
+
(-2, 3)
|
435 |
+
|
436 |
+
Rationals are also recognized:
|
437 |
+
|
438 |
+
>>> perfect_power(Rational(1, 2)**3)
|
439 |
+
(1/2, 3)
|
440 |
+
>>> perfect_power(Rational(-3, 2)**3)
|
441 |
+
(-3/2, 3)
|
442 |
+
|
443 |
+
Notes
|
444 |
+
=====
|
445 |
+
|
446 |
+
To know whether an integer is a perfect power of 2 use
|
447 |
+
|
448 |
+
>>> is2pow = lambda n: bool(n and not n & (n - 1))
|
449 |
+
>>> [(i, is2pow(i)) for i in range(5)]
|
450 |
+
[(0, False), (1, True), (2, True), (3, False), (4, True)]
|
451 |
+
|
452 |
+
It is not necessary to provide ``candidates``. When provided
|
453 |
+
it will be assumed that they are ints. The first one that is
|
454 |
+
larger than the computed maximum possible exponent will signal
|
455 |
+
failure for the routine.
|
456 |
+
|
457 |
+
>>> perfect_power(3**8, [9])
|
458 |
+
False
|
459 |
+
>>> perfect_power(3**8, [2, 4, 8])
|
460 |
+
(3, 8)
|
461 |
+
>>> perfect_power(3**8, [4, 8], big=False)
|
462 |
+
(9, 4)
|
463 |
+
|
464 |
+
See Also
|
465 |
+
========
|
466 |
+
sympy.core.power.integer_nthroot
|
467 |
+
sympy.ntheory.primetest.is_square
|
468 |
+
"""
|
469 |
+
if isinstance(n, Rational) and not n.is_Integer:
|
470 |
+
p, q = n.as_numer_denom()
|
471 |
+
if p is S.One:
|
472 |
+
pp = perfect_power(q)
|
473 |
+
if pp:
|
474 |
+
pp = (n.func(1, pp[0]), pp[1])
|
475 |
+
else:
|
476 |
+
pp = perfect_power(p)
|
477 |
+
if pp:
|
478 |
+
num, e = pp
|
479 |
+
pq = perfect_power(q, [e])
|
480 |
+
if pq:
|
481 |
+
den, _ = pq
|
482 |
+
pp = n.func(num, den), e
|
483 |
+
return pp
|
484 |
+
|
485 |
+
n = as_int(n)
|
486 |
+
if n < 0:
|
487 |
+
pp = perfect_power(-n)
|
488 |
+
if pp:
|
489 |
+
b, e = pp
|
490 |
+
if e % 2:
|
491 |
+
return -b, e
|
492 |
+
return False
|
493 |
+
|
494 |
+
if n <= 3:
|
495 |
+
# no unique exponent for 0, 1
|
496 |
+
# 2 and 3 have exponents of 1
|
497 |
+
return False
|
498 |
+
logn = math.log(n, 2)
|
499 |
+
max_possible = int(logn) + 2 # only check values less than this
|
500 |
+
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
|
501 |
+
min_possible = 2 + not_square
|
502 |
+
if not candidates:
|
503 |
+
candidates = primerange(min_possible, max_possible)
|
504 |
+
else:
|
505 |
+
candidates = sorted([i for i in candidates
|
506 |
+
if min_possible <= i < max_possible])
|
507 |
+
if n%2 == 0:
|
508 |
+
e = trailing(n)
|
509 |
+
candidates = [i for i in candidates if e%i == 0]
|
510 |
+
if big:
|
511 |
+
candidates = reversed(candidates)
|
512 |
+
for e in candidates:
|
513 |
+
r, ok = integer_nthroot(n, e)
|
514 |
+
if ok:
|
515 |
+
return (r, e)
|
516 |
+
return False
|
517 |
+
|
518 |
+
def _factors():
|
519 |
+
rv = 2 + n % 2
|
520 |
+
while True:
|
521 |
+
yield rv
|
522 |
+
rv = nextprime(rv)
|
523 |
+
|
524 |
+
for fac, e in zip(_factors(), candidates):
|
525 |
+
# see if there is a factor present
|
526 |
+
if factor and n % fac == 0:
|
527 |
+
# find what the potential power is
|
528 |
+
if fac == 2:
|
529 |
+
e = trailing(n)
|
530 |
+
else:
|
531 |
+
e = multiplicity(fac, n)
|
532 |
+
# if it's a trivial power we are done
|
533 |
+
if e == 1:
|
534 |
+
return False
|
535 |
+
|
536 |
+
# maybe the e-th root of n is exact
|
537 |
+
r, exact = integer_nthroot(n, e)
|
538 |
+
if not exact:
|
539 |
+
# Having a factor, we know that e is the maximal
|
540 |
+
# possible value for a root of n.
|
541 |
+
# If n = fac**e*m can be written as a perfect
|
542 |
+
# power then see if m can be written as r**E where
|
543 |
+
# gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
|
544 |
+
m = n//fac**e
|
545 |
+
rE = perfect_power(m, candidates=divisors(e, generator=True))
|
546 |
+
if not rE:
|
547 |
+
return False
|
548 |
+
else:
|
549 |
+
r, E = rE
|
550 |
+
r, e = fac**(e//E)*r, E
|
551 |
+
if not big:
|
552 |
+
e0 = primefactors(e)
|
553 |
+
if e0[0] != e:
|
554 |
+
r, e = r**(e//e0[0]), e0[0]
|
555 |
+
return r, e
|
556 |
+
|
557 |
+
# Weed out downright impossible candidates
|
558 |
+
if logn/e < 40:
|
559 |
+
b = 2.0**(logn/e)
|
560 |
+
if abs(int(b + 0.5) - b) > 0.01:
|
561 |
+
continue
|
562 |
+
|
563 |
+
# now see if the plausible e makes a perfect power
|
564 |
+
r, exact = integer_nthroot(n, e)
|
565 |
+
if exact:
|
566 |
+
if big:
|
567 |
+
m = perfect_power(r, big=big, factor=factor)
|
568 |
+
if m:
|
569 |
+
r, e = m[0], e*m[1]
|
570 |
+
return int(r), e
|
571 |
+
|
572 |
+
return False
|
573 |
+
|
574 |
+
|
575 |
+
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
|
576 |
+
r"""
|
577 |
+
Use Pollard's rho method to try to extract a nontrivial factor
|
578 |
+
of ``n``. The returned factor may be a composite number. If no
|
579 |
+
factor is found, ``None`` is returned.
|
580 |
+
|
581 |
+
The algorithm generates pseudo-random values of x with a generator
|
582 |
+
function, replacing x with F(x). If F is not supplied then the
|
583 |
+
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
|
584 |
+
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
|
585 |
+
supplied; the ``a`` will be ignored if F was supplied.
|
586 |
+
|
587 |
+
The sequence of numbers generated by such functions generally have a
|
588 |
+
a lead-up to some number and then loop around back to that number and
|
589 |
+
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
|
590 |
+
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
|
591 |
+
|
592 |
+
For a given function, very different leader-loop values can be obtained
|
593 |
+
so it is a good idea to allow for retries:
|
594 |
+
|
595 |
+
>>> from sympy.ntheory.generate import cycle_length
|
596 |
+
>>> n = 16843009
|
597 |
+
>>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
|
598 |
+
>>> for s in range(5):
|
599 |
+
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
|
600 |
+
...
|
601 |
+
loop length = 2489; leader length = 42
|
602 |
+
loop length = 78; leader length = 120
|
603 |
+
loop length = 1482; leader length = 99
|
604 |
+
loop length = 1482; leader length = 285
|
605 |
+
loop length = 1482; leader length = 100
|
606 |
+
|
607 |
+
Here is an explicit example where there is a two element leadup to
|
608 |
+
a sequence of 3 numbers (11, 14, 4) that then repeat:
|
609 |
+
|
610 |
+
>>> x=2
|
611 |
+
>>> for i in range(9):
|
612 |
+
... x=(x**2+12)%17
|
613 |
+
... print(x)
|
614 |
+
...
|
615 |
+
16
|
616 |
+
13
|
617 |
+
11
|
618 |
+
14
|
619 |
+
4
|
620 |
+
11
|
621 |
+
14
|
622 |
+
4
|
623 |
+
11
|
624 |
+
>>> next(cycle_length(lambda x: (x**2+12)%17, 2))
|
625 |
+
(3, 2)
|
626 |
+
>>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
|
627 |
+
[16, 13, 11, 14, 4]
|
628 |
+
|
629 |
+
Instead of checking the differences of all generated values for a gcd
|
630 |
+
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
|
631 |
+
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
|
632 |
+
traversed. Loops may be many thousands of steps long before rho finds a
|
633 |
+
factor or reports failure. If ``max_steps`` is specified, the iteration
|
634 |
+
is cancelled with a failure after the specified number of steps.
|
635 |
+
|
636 |
+
Examples
|
637 |
+
========
|
638 |
+
|
639 |
+
>>> from sympy import pollard_rho
|
640 |
+
>>> n=16843009
|
641 |
+
>>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
|
642 |
+
>>> pollard_rho(n, F=F)
|
643 |
+
257
|
644 |
+
|
645 |
+
Use the default setting with a bad value of ``a`` and no retries:
|
646 |
+
|
647 |
+
>>> pollard_rho(n, a=n-2, retries=0)
|
648 |
+
|
649 |
+
If retries is > 0 then perhaps the problem will correct itself when
|
650 |
+
new values are generated for a:
|
651 |
+
|
652 |
+
>>> pollard_rho(n, a=n-2, retries=1)
|
653 |
+
257
|
654 |
+
|
655 |
+
References
|
656 |
+
==========
|
657 |
+
|
658 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
659 |
+
A Computational Perspective", Springer, 2nd edition, 229-231
|
660 |
+
|
661 |
+
"""
|
662 |
+
n = int(n)
|
663 |
+
if n < 5:
|
664 |
+
raise ValueError('pollard_rho should receive n > 4')
|
665 |
+
prng = random.Random(seed + retries)
|
666 |
+
V = s
|
667 |
+
for i in range(retries + 1):
|
668 |
+
U = V
|
669 |
+
if not F:
|
670 |
+
F = lambda x: (pow(x, 2, n) + a) % n
|
671 |
+
j = 0
|
672 |
+
while 1:
|
673 |
+
if max_steps and (j > max_steps):
|
674 |
+
break
|
675 |
+
j += 1
|
676 |
+
U = F(U)
|
677 |
+
V = F(F(V)) # V is 2x further along than U
|
678 |
+
g = igcd(U - V, n)
|
679 |
+
if g == 1:
|
680 |
+
continue
|
681 |
+
if g == n:
|
682 |
+
break
|
683 |
+
return int(g)
|
684 |
+
V = prng.randint(0, n - 1)
|
685 |
+
a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
|
686 |
+
F = None
|
687 |
+
return None
|
688 |
+
|
689 |
+
|
690 |
+
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
|
691 |
+
"""
|
692 |
+
Use Pollard's p-1 method to try to extract a nontrivial factor
|
693 |
+
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
|
694 |
+
|
695 |
+
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
|
696 |
+
The default is 2. If ``retries`` > 0 then if no factor is found after the
|
697 |
+
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
|
698 |
+
and the process repeated.
|
699 |
+
|
700 |
+
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
|
701 |
+
|
702 |
+
A search is made for factors next to even numbers having a power smoothness
|
703 |
+
less than ``B``. Choosing a larger B increases the likelihood of finding a
|
704 |
+
larger factor but takes longer. Whether a factor of n is found or not
|
705 |
+
depends on ``a`` and the power smoothness of the even number just less than
|
706 |
+
the factor p (hence the name p - 1).
|
707 |
+
|
708 |
+
Although some discussion of what constitutes a good ``a`` some
|
709 |
+
descriptions are hard to interpret. At the modular.math site referenced
|
710 |
+
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
|
711 |
+
for every prime power divisor of N. But consider the following:
|
712 |
+
|
713 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
|
714 |
+
>>> n=257*1009
|
715 |
+
>>> smoothness_p(n)
|
716 |
+
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
|
717 |
+
|
718 |
+
So we should (and can) find a root with B=16:
|
719 |
+
|
720 |
+
>>> pollard_pm1(n, B=16, a=3)
|
721 |
+
1009
|
722 |
+
|
723 |
+
If we attempt to increase B to 256 we find that it does not work:
|
724 |
+
|
725 |
+
>>> pollard_pm1(n, B=256)
|
726 |
+
>>>
|
727 |
+
|
728 |
+
But if the value of ``a`` is changed we find that only multiples of
|
729 |
+
257 work, e.g.:
|
730 |
+
|
731 |
+
>>> pollard_pm1(n, B=256, a=257)
|
732 |
+
1009
|
733 |
+
|
734 |
+
Checking different ``a`` values shows that all the ones that did not
|
735 |
+
work had a gcd value not equal to ``n`` but equal to one of the
|
736 |
+
factors:
|
737 |
+
|
738 |
+
>>> from sympy import ilcm, igcd, factorint, Pow
|
739 |
+
>>> M = 1
|
740 |
+
>>> for i in range(2, 256):
|
741 |
+
... M = ilcm(M, i)
|
742 |
+
...
|
743 |
+
>>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
|
744 |
+
... igcd(pow(a, M, n) - 1, n) != n])
|
745 |
+
{1009}
|
746 |
+
|
747 |
+
But does aM % d for every divisor of n give 1?
|
748 |
+
|
749 |
+
>>> aM = pow(255, M, n)
|
750 |
+
>>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
|
751 |
+
[(257**1, 1), (1009**1, 1)]
|
752 |
+
|
753 |
+
No, only one of them. So perhaps the principle is that a root will
|
754 |
+
be found for a given value of B provided that:
|
755 |
+
|
756 |
+
1) the power smoothness of the p - 1 value next to the root
|
757 |
+
does not exceed B
|
758 |
+
2) a**M % p != 1 for any of the divisors of n.
|
759 |
+
|
760 |
+
By trying more than one ``a`` it is possible that one of them
|
761 |
+
will yield a factor.
|
762 |
+
|
763 |
+
Examples
|
764 |
+
========
|
765 |
+
|
766 |
+
With the default smoothness bound, this number cannot be cracked:
|
767 |
+
|
768 |
+
>>> from sympy.ntheory import pollard_pm1
|
769 |
+
>>> pollard_pm1(21477639576571)
|
770 |
+
|
771 |
+
Increasing the smoothness bound helps:
|
772 |
+
|
773 |
+
>>> pollard_pm1(21477639576571, B=2000)
|
774 |
+
4410317
|
775 |
+
|
776 |
+
Looking at the smoothness of the factors of this number we find:
|
777 |
+
|
778 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
|
779 |
+
>>> print(smoothness_p(21477639576571, visual=1))
|
780 |
+
p**i=4410317**1 has p-1 B=1787, B-pow=1787
|
781 |
+
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
|
782 |
+
|
783 |
+
The B and B-pow are the same for the p - 1 factorizations of the divisors
|
784 |
+
because those factorizations had a very large prime factor:
|
785 |
+
|
786 |
+
>>> factorint(4410317 - 1)
|
787 |
+
{2: 2, 617: 1, 1787: 1}
|
788 |
+
>>> factorint(4869863-1)
|
789 |
+
{2: 1, 2434931: 1}
|
790 |
+
|
791 |
+
Note that until B reaches the B-pow value of 1787, the number is not cracked;
|
792 |
+
|
793 |
+
>>> pollard_pm1(21477639576571, B=1786)
|
794 |
+
>>> pollard_pm1(21477639576571, B=1787)
|
795 |
+
4410317
|
796 |
+
|
797 |
+
The B value has to do with the factors of the number next to the divisor,
|
798 |
+
not the divisors themselves. A worst case scenario is that the number next
|
799 |
+
to the factor p has a large prime divisisor or is a perfect power. If these
|
800 |
+
conditions apply then the power-smoothness will be about p/2 or p. The more
|
801 |
+
realistic is that there will be a large prime factor next to p requiring
|
802 |
+
a B value on the order of p/2. Although primes may have been searched for
|
803 |
+
up to this level, the p/2 is a factor of p - 1, something that we do not
|
804 |
+
know. The modular.math reference below states that 15% of numbers in the
|
805 |
+
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
|
806 |
+
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
|
807 |
+
percentages are nearly reversed...but in that range the simple trial
|
808 |
+
division is quite fast.
|
809 |
+
|
810 |
+
References
|
811 |
+
==========
|
812 |
+
|
813 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
814 |
+
A Computational Perspective", Springer, 2nd edition, 236-238
|
815 |
+
.. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
|
816 |
+
.. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
|
817 |
+
"""
|
818 |
+
|
819 |
+
n = int(n)
|
820 |
+
if n < 4 or B < 3:
|
821 |
+
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
|
822 |
+
prng = random.Random(seed + B)
|
823 |
+
|
824 |
+
# computing a**lcm(1,2,3,..B) % n for B > 2
|
825 |
+
# it looks weird, but it's right: primes run [2, B]
|
826 |
+
# and the answer's not right until the loop is done.
|
827 |
+
for i in range(retries + 1):
|
828 |
+
aM = a
|
829 |
+
for p in sieve.primerange(2, B + 1):
|
830 |
+
e = int(math.log(B, p))
|
831 |
+
aM = pow(aM, pow(p, e), n)
|
832 |
+
g = igcd(aM - 1, n)
|
833 |
+
if 1 < g < n:
|
834 |
+
return int(g)
|
835 |
+
|
836 |
+
# get a new a:
|
837 |
+
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
|
838 |
+
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
|
839 |
+
# give a zero, too, so we set the range as [2, n-2]. Some references
|
840 |
+
# say 'a' should be coprime to n, but either will detect factors.
|
841 |
+
a = prng.randint(2, n - 2)
|
842 |
+
|
843 |
+
|
844 |
+
def _trial(factors, n, candidates, verbose=False):
|
845 |
+
"""
|
846 |
+
Helper function for integer factorization. Trial factors ``n`
|
847 |
+
against all integers given in the sequence ``candidates``
|
848 |
+
and updates the dict ``factors`` in-place. Returns the reduced
|
849 |
+
value of ``n`` and a flag indicating whether any factors were found.
|
850 |
+
"""
|
851 |
+
if verbose:
|
852 |
+
factors0 = list(factors.keys())
|
853 |
+
nfactors = len(factors)
|
854 |
+
for d in candidates:
|
855 |
+
if n % d == 0:
|
856 |
+
m = multiplicity(d, n)
|
857 |
+
n //= d**m
|
858 |
+
factors[d] = m
|
859 |
+
if verbose:
|
860 |
+
for k in sorted(set(factors).difference(set(factors0))):
|
861 |
+
print(factor_msg % (k, factors[k]))
|
862 |
+
return int(n), len(factors) != nfactors
|
863 |
+
|
864 |
+
|
865 |
+
def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1,
|
866 |
+
verbose):
|
867 |
+
"""
|
868 |
+
Helper function for integer factorization. Checks if ``n``
|
869 |
+
is a prime or a perfect power, and in those cases updates
|
870 |
+
the factorization and raises ``StopIteration``.
|
871 |
+
"""
|
872 |
+
|
873 |
+
if verbose:
|
874 |
+
print('Check for termination')
|
875 |
+
|
876 |
+
# since we've already been factoring there is no need to do
|
877 |
+
# simultaneous factoring with the power check
|
878 |
+
p = perfect_power(n, factor=False)
|
879 |
+
if p is not False:
|
880 |
+
base, exp = p
|
881 |
+
if limitp1:
|
882 |
+
limit = limitp1 - 1
|
883 |
+
else:
|
884 |
+
limit = limitp1
|
885 |
+
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
|
886 |
+
verbose=False)
|
887 |
+
for b, e in facs.items():
|
888 |
+
if verbose:
|
889 |
+
print(factor_msg % (b, e))
|
890 |
+
factors[b] = exp*e
|
891 |
+
raise StopIteration
|
892 |
+
|
893 |
+
if isprime(n):
|
894 |
+
factors[int(n)] = 1
|
895 |
+
raise StopIteration
|
896 |
+
|
897 |
+
if n == 1:
|
898 |
+
raise StopIteration
|
899 |
+
|
900 |
+
trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
|
901 |
+
trial_msg = "Trial division with primes [%i ... %i]"
|
902 |
+
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
|
903 |
+
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
|
904 |
+
ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
|
905 |
+
factor_msg = '\t%i ** %i'
|
906 |
+
fermat_msg = 'Close factors satisying Fermat condition found.'
|
907 |
+
complete_msg = 'Factorization is complete.'
|
908 |
+
|
909 |
+
|
910 |
+
def _factorint_small(factors, n, limit, fail_max):
|
911 |
+
"""
|
912 |
+
Return the value of n and either a 0 (indicating that factorization up
|
913 |
+
to the limit was complete) or else the next near-prime that would have
|
914 |
+
been tested.
|
915 |
+
|
916 |
+
Factoring stops if there are fail_max unsuccessful tests in a row.
|
917 |
+
|
918 |
+
If factors of n were found they will be in the factors dictionary as
|
919 |
+
{factor: multiplicity} and the returned value of n will have had those
|
920 |
+
factors removed. The factors dictionary is modified in-place.
|
921 |
+
|
922 |
+
"""
|
923 |
+
|
924 |
+
def done(n, d):
|
925 |
+
"""return n, d if the sqrt(n) was not reached yet, else
|
926 |
+
n, 0 indicating that factoring is done.
|
927 |
+
"""
|
928 |
+
if d*d <= n:
|
929 |
+
return n, d
|
930 |
+
return n, 0
|
931 |
+
|
932 |
+
d = 2
|
933 |
+
m = trailing(n)
|
934 |
+
if m:
|
935 |
+
factors[d] = m
|
936 |
+
n >>= m
|
937 |
+
d = 3
|
938 |
+
if limit < d:
|
939 |
+
if n > 1:
|
940 |
+
factors[n] = 1
|
941 |
+
return done(n, d)
|
942 |
+
# reduce
|
943 |
+
m = 0
|
944 |
+
while n % d == 0:
|
945 |
+
n //= d
|
946 |
+
m += 1
|
947 |
+
if m == 20:
|
948 |
+
mm = multiplicity(d, n)
|
949 |
+
m += mm
|
950 |
+
n //= d**mm
|
951 |
+
break
|
952 |
+
if m:
|
953 |
+
factors[d] = m
|
954 |
+
|
955 |
+
# when d*d exceeds maxx or n we are done; if limit**2 is greater
|
956 |
+
# than n then maxx is set to zero so the value of n will flag the finish
|
957 |
+
if limit*limit > n:
|
958 |
+
maxx = 0
|
959 |
+
else:
|
960 |
+
maxx = limit*limit
|
961 |
+
|
962 |
+
dd = maxx or n
|
963 |
+
d = 5
|
964 |
+
fails = 0
|
965 |
+
while fails < fail_max:
|
966 |
+
if d*d > dd:
|
967 |
+
break
|
968 |
+
# d = 6*i - 1
|
969 |
+
# reduce
|
970 |
+
m = 0
|
971 |
+
while n % d == 0:
|
972 |
+
n //= d
|
973 |
+
m += 1
|
974 |
+
if m == 20:
|
975 |
+
mm = multiplicity(d, n)
|
976 |
+
m += mm
|
977 |
+
n //= d**mm
|
978 |
+
break
|
979 |
+
if m:
|
980 |
+
factors[d] = m
|
981 |
+
dd = maxx or n
|
982 |
+
fails = 0
|
983 |
+
else:
|
984 |
+
fails += 1
|
985 |
+
d += 2
|
986 |
+
if d*d > dd:
|
987 |
+
break
|
988 |
+
# d = 6*i - 1
|
989 |
+
# reduce
|
990 |
+
m = 0
|
991 |
+
while n % d == 0:
|
992 |
+
n //= d
|
993 |
+
m += 1
|
994 |
+
if m == 20:
|
995 |
+
mm = multiplicity(d, n)
|
996 |
+
m += mm
|
997 |
+
n //= d**mm
|
998 |
+
break
|
999 |
+
if m:
|
1000 |
+
factors[d] = m
|
1001 |
+
dd = maxx or n
|
1002 |
+
fails = 0
|
1003 |
+
else:
|
1004 |
+
fails += 1
|
1005 |
+
# d = 6*(i + 1) - 1
|
1006 |
+
d += 4
|
1007 |
+
|
1008 |
+
return done(n, d)
|
1009 |
+
|
1010 |
+
|
1011 |
+
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
|
1012 |
+
use_ecm=True, verbose=False, visual=None, multiple=False):
|
1013 |
+
r"""
|
1014 |
+
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
|
1015 |
+
the prime factors of ``n`` as keys and their respective multiplicities
|
1016 |
+
as values. For example:
|
1017 |
+
|
1018 |
+
>>> from sympy.ntheory import factorint
|
1019 |
+
>>> factorint(2000) # 2000 = (2**4) * (5**3)
|
1020 |
+
{2: 4, 5: 3}
|
1021 |
+
>>> factorint(65537) # This number is prime
|
1022 |
+
{65537: 1}
|
1023 |
+
|
1024 |
+
For input less than 2, factorint behaves as follows:
|
1025 |
+
|
1026 |
+
- ``factorint(1)`` returns the empty factorization, ``{}``
|
1027 |
+
- ``factorint(0)`` returns ``{0:1}``
|
1028 |
+
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
|
1029 |
+
|
1030 |
+
Partial Factorization:
|
1031 |
+
|
1032 |
+
If ``limit`` (> 3) is specified, the search is stopped after performing
|
1033 |
+
trial division up to (and including) the limit (or taking a
|
1034 |
+
corresponding number of rho/p-1 steps). This is useful if one has
|
1035 |
+
a large number and only is interested in finding small factors (if
|
1036 |
+
any). Note that setting a limit does not prevent larger factors
|
1037 |
+
from being found early; it simply means that the largest factor may
|
1038 |
+
be composite. Since checking for perfect power is relatively cheap, it is
|
1039 |
+
done regardless of the limit setting.
|
1040 |
+
|
1041 |
+
This number, for example, has two small factors and a huge
|
1042 |
+
semi-prime factor that cannot be reduced easily:
|
1043 |
+
|
1044 |
+
>>> from sympy.ntheory import isprime
|
1045 |
+
>>> a = 1407633717262338957430697921446883
|
1046 |
+
>>> f = factorint(a, limit=10000)
|
1047 |
+
>>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
|
1048 |
+
True
|
1049 |
+
>>> isprime(max(f))
|
1050 |
+
False
|
1051 |
+
|
1052 |
+
This number has a small factor and a residual perfect power whose
|
1053 |
+
base is greater than the limit:
|
1054 |
+
|
1055 |
+
>>> factorint(3*101**7, limit=5)
|
1056 |
+
{3: 1, 101: 7}
|
1057 |
+
|
1058 |
+
List of Factors:
|
1059 |
+
|
1060 |
+
If ``multiple`` is set to ``True`` then a list containing the
|
1061 |
+
prime factors including multiplicities is returned.
|
1062 |
+
|
1063 |
+
>>> factorint(24, multiple=True)
|
1064 |
+
[2, 2, 2, 3]
|
1065 |
+
|
1066 |
+
Visual Factorization:
|
1067 |
+
|
1068 |
+
If ``visual`` is set to ``True``, then it will return a visual
|
1069 |
+
factorization of the integer. For example:
|
1070 |
+
|
1071 |
+
>>> from sympy import pprint
|
1072 |
+
>>> pprint(factorint(4200, visual=True))
|
1073 |
+
3 1 2 1
|
1074 |
+
2 *3 *5 *7
|
1075 |
+
|
1076 |
+
Note that this is achieved by using the evaluate=False flag in Mul
|
1077 |
+
and Pow. If you do other manipulations with an expression where
|
1078 |
+
evaluate=False, it may evaluate. Therefore, you should use the
|
1079 |
+
visual option only for visualization, and use the normal dictionary
|
1080 |
+
returned by visual=False if you want to perform operations on the
|
1081 |
+
factors.
|
1082 |
+
|
1083 |
+
You can easily switch between the two forms by sending them back to
|
1084 |
+
factorint:
|
1085 |
+
|
1086 |
+
>>> from sympy import Mul
|
1087 |
+
>>> regular = factorint(1764); regular
|
1088 |
+
{2: 2, 3: 2, 7: 2}
|
1089 |
+
>>> pprint(factorint(regular))
|
1090 |
+
2 2 2
|
1091 |
+
2 *3 *7
|
1092 |
+
|
1093 |
+
>>> visual = factorint(1764, visual=True); pprint(visual)
|
1094 |
+
2 2 2
|
1095 |
+
2 *3 *7
|
1096 |
+
>>> print(factorint(visual))
|
1097 |
+
{2: 2, 3: 2, 7: 2}
|
1098 |
+
|
1099 |
+
If you want to send a number to be factored in a partially factored form
|
1100 |
+
you can do so with a dictionary or unevaluated expression:
|
1101 |
+
|
1102 |
+
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
|
1103 |
+
{2: 10, 3: 3}
|
1104 |
+
>>> factorint(Mul(4, 12, evaluate=False))
|
1105 |
+
{2: 4, 3: 1}
|
1106 |
+
|
1107 |
+
The table of the output logic is:
|
1108 |
+
|
1109 |
+
====== ====== ======= =======
|
1110 |
+
Visual
|
1111 |
+
------ ----------------------
|
1112 |
+
Input True False other
|
1113 |
+
====== ====== ======= =======
|
1114 |
+
dict mul dict mul
|
1115 |
+
n mul dict dict
|
1116 |
+
mul mul dict dict
|
1117 |
+
====== ====== ======= =======
|
1118 |
+
|
1119 |
+
Notes
|
1120 |
+
=====
|
1121 |
+
|
1122 |
+
Algorithm:
|
1123 |
+
|
1124 |
+
The function switches between multiple algorithms. Trial division
|
1125 |
+
quickly finds small factors (of the order 1-5 digits), and finds
|
1126 |
+
all large factors if given enough time. The Pollard rho and p-1
|
1127 |
+
algorithms are used to find large factors ahead of time; they
|
1128 |
+
will often find factors of the order of 10 digits within a few
|
1129 |
+
seconds:
|
1130 |
+
|
1131 |
+
>>> factors = factorint(12345678910111213141516)
|
1132 |
+
>>> for base, exp in sorted(factors.items()):
|
1133 |
+
... print('%s %s' % (base, exp))
|
1134 |
+
...
|
1135 |
+
2 2
|
1136 |
+
2507191691 1
|
1137 |
+
1231026625769 1
|
1138 |
+
|
1139 |
+
Any of these methods can optionally be disabled with the following
|
1140 |
+
boolean parameters:
|
1141 |
+
|
1142 |
+
- ``use_trial``: Toggle use of trial division
|
1143 |
+
- ``use_rho``: Toggle use of Pollard's rho method
|
1144 |
+
- ``use_pm1``: Toggle use of Pollard's p-1 method
|
1145 |
+
|
1146 |
+
``factorint`` also periodically checks if the remaining part is
|
1147 |
+
a prime number or a perfect power, and in those cases stops.
|
1148 |
+
|
1149 |
+
For unevaluated factorial, it uses Legendre's formula(theorem).
|
1150 |
+
|
1151 |
+
|
1152 |
+
If ``verbose`` is set to ``True``, detailed progress is printed.
|
1153 |
+
|
1154 |
+
See Also
|
1155 |
+
========
|
1156 |
+
|
1157 |
+
smoothness, smoothness_p, divisors
|
1158 |
+
|
1159 |
+
"""
|
1160 |
+
if isinstance(n, Dict):
|
1161 |
+
n = dict(n)
|
1162 |
+
if multiple:
|
1163 |
+
fac = factorint(n, limit=limit, use_trial=use_trial,
|
1164 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
1165 |
+
verbose=verbose, visual=False, multiple=False)
|
1166 |
+
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
|
1167 |
+
for p in sorted(fac)), [])
|
1168 |
+
return factorlist
|
1169 |
+
|
1170 |
+
factordict = {}
|
1171 |
+
if visual and not isinstance(n, (Mul, dict)):
|
1172 |
+
factordict = factorint(n, limit=limit, use_trial=use_trial,
|
1173 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
1174 |
+
verbose=verbose, visual=False)
|
1175 |
+
elif isinstance(n, Mul):
|
1176 |
+
factordict = {int(k): int(v) for k, v in
|
1177 |
+
n.as_powers_dict().items()}
|
1178 |
+
elif isinstance(n, dict):
|
1179 |
+
factordict = n
|
1180 |
+
if factordict and isinstance(n, (Mul, dict)):
|
1181 |
+
# check it
|
1182 |
+
for key in list(factordict.keys()):
|
1183 |
+
if isprime(key):
|
1184 |
+
continue
|
1185 |
+
e = factordict.pop(key)
|
1186 |
+
d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
|
1187 |
+
use_pm1=use_pm1, verbose=verbose, visual=False)
|
1188 |
+
for k, v in d.items():
|
1189 |
+
if k in factordict:
|
1190 |
+
factordict[k] += v*e
|
1191 |
+
else:
|
1192 |
+
factordict[k] = v*e
|
1193 |
+
if visual or (type(n) is dict and
|
1194 |
+
visual is not True and
|
1195 |
+
visual is not False):
|
1196 |
+
if factordict == {}:
|
1197 |
+
return S.One
|
1198 |
+
if -1 in factordict:
|
1199 |
+
factordict.pop(-1)
|
1200 |
+
args = [S.NegativeOne]
|
1201 |
+
else:
|
1202 |
+
args = []
|
1203 |
+
args.extend([Pow(*i, evaluate=False)
|
1204 |
+
for i in sorted(factordict.items())])
|
1205 |
+
return Mul(*args, evaluate=False)
|
1206 |
+
elif isinstance(n, (dict, Mul)):
|
1207 |
+
return factordict
|
1208 |
+
|
1209 |
+
assert use_trial or use_rho or use_pm1 or use_ecm
|
1210 |
+
|
1211 |
+
from sympy.functions.combinatorial.factorials import factorial
|
1212 |
+
if isinstance(n, factorial):
|
1213 |
+
x = as_int(n.args[0])
|
1214 |
+
if x >= 20:
|
1215 |
+
factors = {}
|
1216 |
+
m = 2 # to initialize the if condition below
|
1217 |
+
for p in sieve.primerange(2, x + 1):
|
1218 |
+
if m > 1:
|
1219 |
+
m, q = 0, x // p
|
1220 |
+
while q != 0:
|
1221 |
+
m += q
|
1222 |
+
q //= p
|
1223 |
+
factors[p] = m
|
1224 |
+
if factors and verbose:
|
1225 |
+
for k in sorted(factors):
|
1226 |
+
print(factor_msg % (k, factors[k]))
|
1227 |
+
if verbose:
|
1228 |
+
print(complete_msg)
|
1229 |
+
return factors
|
1230 |
+
else:
|
1231 |
+
# if n < 20!, direct computation is faster
|
1232 |
+
# since it uses a lookup table
|
1233 |
+
n = n.func(x)
|
1234 |
+
|
1235 |
+
n = as_int(n)
|
1236 |
+
if limit:
|
1237 |
+
limit = int(limit)
|
1238 |
+
use_ecm = False
|
1239 |
+
|
1240 |
+
# special cases
|
1241 |
+
if n < 0:
|
1242 |
+
factors = factorint(
|
1243 |
+
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
|
1244 |
+
use_pm1=use_pm1, verbose=verbose, visual=False)
|
1245 |
+
factors[-1] = 1
|
1246 |
+
return factors
|
1247 |
+
|
1248 |
+
if limit and limit < 2:
|
1249 |
+
if n == 1:
|
1250 |
+
return {}
|
1251 |
+
return {n: 1}
|
1252 |
+
elif n < 10:
|
1253 |
+
# doing this we are assured of getting a limit > 2
|
1254 |
+
# when we have to compute it later
|
1255 |
+
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
|
1256 |
+
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
|
1257 |
+
|
1258 |
+
factors = {}
|
1259 |
+
|
1260 |
+
# do simplistic factorization
|
1261 |
+
if verbose:
|
1262 |
+
sn = str(n)
|
1263 |
+
if len(sn) > 50:
|
1264 |
+
print('Factoring %s' % sn[:5] + \
|
1265 |
+
'..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
|
1266 |
+
else:
|
1267 |
+
print('Factoring', n)
|
1268 |
+
|
1269 |
+
if use_trial:
|
1270 |
+
# this is the preliminary factorization for small factors
|
1271 |
+
small = 2**15
|
1272 |
+
fail_max = 600
|
1273 |
+
small = min(small, limit or small)
|
1274 |
+
if verbose:
|
1275 |
+
print(trial_int_msg % (2, small, fail_max))
|
1276 |
+
n, next_p = _factorint_small(factors, n, small, fail_max)
|
1277 |
+
else:
|
1278 |
+
next_p = 2
|
1279 |
+
if factors and verbose:
|
1280 |
+
for k in sorted(factors):
|
1281 |
+
print(factor_msg % (k, factors[k]))
|
1282 |
+
if next_p == 0:
|
1283 |
+
if n > 1:
|
1284 |
+
factors[int(n)] = 1
|
1285 |
+
if verbose:
|
1286 |
+
print(complete_msg)
|
1287 |
+
return factors
|
1288 |
+
|
1289 |
+
# continue with more advanced factorization methods
|
1290 |
+
|
1291 |
+
# first check if the simplistic run didn't finish
|
1292 |
+
# because of the limit and check for a perfect
|
1293 |
+
# power before exiting
|
1294 |
+
try:
|
1295 |
+
if limit and next_p > limit:
|
1296 |
+
if verbose:
|
1297 |
+
print('Exceeded limit:', limit)
|
1298 |
+
|
1299 |
+
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
|
1300 |
+
verbose)
|
1301 |
+
|
1302 |
+
if n > 1:
|
1303 |
+
factors[int(n)] = 1
|
1304 |
+
return factors
|
1305 |
+
else:
|
1306 |
+
# Before quitting (or continuing on)...
|
1307 |
+
|
1308 |
+
# ...do a Fermat test since it's so easy and we need the
|
1309 |
+
# square root anyway. Finding 2 factors is easy if they are
|
1310 |
+
# "close enough." This is the big root equivalent of dividing by
|
1311 |
+
# 2, 3, 5.
|
1312 |
+
sqrt_n = integer_nthroot(n, 2)[0]
|
1313 |
+
a = sqrt_n + 1
|
1314 |
+
a2 = a**2
|
1315 |
+
b2 = a2 - n
|
1316 |
+
for i in range(3):
|
1317 |
+
b, fermat = integer_nthroot(b2, 2)
|
1318 |
+
if fermat:
|
1319 |
+
break
|
1320 |
+
b2 += 2*a + 1 # equiv to (a + 1)**2 - n
|
1321 |
+
a += 1
|
1322 |
+
if fermat:
|
1323 |
+
if verbose:
|
1324 |
+
print(fermat_msg)
|
1325 |
+
if limit:
|
1326 |
+
limit -= 1
|
1327 |
+
for r in [a - b, a + b]:
|
1328 |
+
facs = factorint(r, limit=limit, use_trial=use_trial,
|
1329 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
1330 |
+
verbose=verbose)
|
1331 |
+
for k, v in facs.items():
|
1332 |
+
factors[k] = factors.get(k, 0) + v
|
1333 |
+
raise StopIteration
|
1334 |
+
|
1335 |
+
# ...see if factorization can be terminated
|
1336 |
+
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
|
1337 |
+
verbose)
|
1338 |
+
|
1339 |
+
except StopIteration:
|
1340 |
+
if verbose:
|
1341 |
+
print(complete_msg)
|
1342 |
+
return factors
|
1343 |
+
|
1344 |
+
# these are the limits for trial division which will
|
1345 |
+
# be attempted in parallel with pollard methods
|
1346 |
+
low, high = next_p, 2*next_p
|
1347 |
+
|
1348 |
+
limit = limit or sqrt_n
|
1349 |
+
# add 1 to make sure limit is reached in primerange calls
|
1350 |
+
limit += 1
|
1351 |
+
iteration = 0
|
1352 |
+
while 1:
|
1353 |
+
|
1354 |
+
try:
|
1355 |
+
high_ = high
|
1356 |
+
if limit < high_:
|
1357 |
+
high_ = limit
|
1358 |
+
|
1359 |
+
# Trial division
|
1360 |
+
if use_trial:
|
1361 |
+
if verbose:
|
1362 |
+
print(trial_msg % (low, high_))
|
1363 |
+
ps = sieve.primerange(low, high_)
|
1364 |
+
n, found_trial = _trial(factors, n, ps, verbose)
|
1365 |
+
if found_trial:
|
1366 |
+
_check_termination(factors, n, limit, use_trial, use_rho,
|
1367 |
+
use_pm1, verbose)
|
1368 |
+
else:
|
1369 |
+
found_trial = False
|
1370 |
+
|
1371 |
+
if high > limit:
|
1372 |
+
if verbose:
|
1373 |
+
print('Exceeded limit:', limit)
|
1374 |
+
if n > 1:
|
1375 |
+
factors[int(n)] = 1
|
1376 |
+
raise StopIteration
|
1377 |
+
|
1378 |
+
# Only used advanced methods when no small factors were found
|
1379 |
+
if not found_trial:
|
1380 |
+
if (use_pm1 or use_rho):
|
1381 |
+
high_root = max(int(math.log(high_**0.7)), low, 3)
|
1382 |
+
|
1383 |
+
# Pollard p-1
|
1384 |
+
if use_pm1:
|
1385 |
+
if verbose:
|
1386 |
+
print(pm1_msg % (high_root, high_))
|
1387 |
+
c = pollard_pm1(n, B=high_root, seed=high_)
|
1388 |
+
if c:
|
1389 |
+
# factor it and let _trial do the update
|
1390 |
+
ps = factorint(c, limit=limit - 1,
|
1391 |
+
use_trial=use_trial,
|
1392 |
+
use_rho=use_rho,
|
1393 |
+
use_pm1=use_pm1,
|
1394 |
+
use_ecm=use_ecm,
|
1395 |
+
verbose=verbose)
|
1396 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
1397 |
+
_check_termination(factors, n, limit, use_trial,
|
1398 |
+
use_rho, use_pm1, verbose)
|
1399 |
+
|
1400 |
+
# Pollard rho
|
1401 |
+
if use_rho:
|
1402 |
+
max_steps = high_root
|
1403 |
+
if verbose:
|
1404 |
+
print(rho_msg % (1, max_steps, high_))
|
1405 |
+
c = pollard_rho(n, retries=1, max_steps=max_steps,
|
1406 |
+
seed=high_)
|
1407 |
+
if c:
|
1408 |
+
# factor it and let _trial do the update
|
1409 |
+
ps = factorint(c, limit=limit - 1,
|
1410 |
+
use_trial=use_trial,
|
1411 |
+
use_rho=use_rho,
|
1412 |
+
use_pm1=use_pm1,
|
1413 |
+
use_ecm=use_ecm,
|
1414 |
+
verbose=verbose)
|
1415 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
1416 |
+
_check_termination(factors, n, limit, use_trial,
|
1417 |
+
use_rho, use_pm1, verbose)
|
1418 |
+
|
1419 |
+
except StopIteration:
|
1420 |
+
if verbose:
|
1421 |
+
print(complete_msg)
|
1422 |
+
return factors
|
1423 |
+
#Use subexponential algorithms if use_ecm
|
1424 |
+
#Use pollard algorithms for finding small factors for 3 iterations
|
1425 |
+
#if after small factors the number of digits of n is >= 20 then use ecm
|
1426 |
+
iteration += 1
|
1427 |
+
if use_ecm and iteration >= 3 and len(str(n)) >= 25:
|
1428 |
+
break
|
1429 |
+
low, high = high, high*2
|
1430 |
+
B1 = 10000
|
1431 |
+
B2 = 100*B1
|
1432 |
+
num_curves = 50
|
1433 |
+
while(1):
|
1434 |
+
if verbose:
|
1435 |
+
print(ecm_msg % (B1, B2, num_curves))
|
1436 |
+
while(1):
|
1437 |
+
try:
|
1438 |
+
factor = _ecm_one_factor(n, B1, B2, num_curves)
|
1439 |
+
ps = factorint(factor, limit=limit - 1,
|
1440 |
+
use_trial=use_trial,
|
1441 |
+
use_rho=use_rho,
|
1442 |
+
use_pm1=use_pm1,
|
1443 |
+
use_ecm=use_ecm,
|
1444 |
+
verbose=verbose)
|
1445 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
1446 |
+
_check_termination(factors, n, limit, use_trial,
|
1447 |
+
use_rho, use_pm1, verbose)
|
1448 |
+
except ValueError:
|
1449 |
+
break
|
1450 |
+
except StopIteration:
|
1451 |
+
if verbose:
|
1452 |
+
print(complete_msg)
|
1453 |
+
return factors
|
1454 |
+
B1 *= 5
|
1455 |
+
B2 = 100*B1
|
1456 |
+
num_curves *= 4
|
1457 |
+
|
1458 |
+
|
1459 |
+
def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
|
1460 |
+
verbose=False, visual=None, multiple=False):
|
1461 |
+
r"""
|
1462 |
+
Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
|
1463 |
+
the prime factors of ``r`` as keys and their respective multiplicities
|
1464 |
+
as values. For example:
|
1465 |
+
|
1466 |
+
>>> from sympy import factorrat, S
|
1467 |
+
>>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
|
1468 |
+
{2: 3, 3: -2}
|
1469 |
+
>>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
|
1470 |
+
{-1: 1, 3: -1, 7: -1, 47: -1}
|
1471 |
+
|
1472 |
+
Please see the docstring for ``factorint`` for detailed explanations
|
1473 |
+
and examples of the following keywords:
|
1474 |
+
|
1475 |
+
- ``limit``: Integer limit up to which trial division is done
|
1476 |
+
- ``use_trial``: Toggle use of trial division
|
1477 |
+
- ``use_rho``: Toggle use of Pollard's rho method
|
1478 |
+
- ``use_pm1``: Toggle use of Pollard's p-1 method
|
1479 |
+
- ``verbose``: Toggle detailed printing of progress
|
1480 |
+
- ``multiple``: Toggle returning a list of factors or dict
|
1481 |
+
- ``visual``: Toggle product form of output
|
1482 |
+
"""
|
1483 |
+
if multiple:
|
1484 |
+
fac = factorrat(rat, limit=limit, use_trial=use_trial,
|
1485 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
1486 |
+
verbose=verbose, visual=False, multiple=False)
|
1487 |
+
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
|
1488 |
+
for p, _ in sorted(fac.items(),
|
1489 |
+
key=lambda elem: elem[0]
|
1490 |
+
if elem[1] > 0
|
1491 |
+
else 1/elem[0])), [])
|
1492 |
+
return factorlist
|
1493 |
+
|
1494 |
+
f = factorint(rat.p, limit=limit, use_trial=use_trial,
|
1495 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
1496 |
+
verbose=verbose).copy()
|
1497 |
+
f = defaultdict(int, f)
|
1498 |
+
for p, e in factorint(rat.q, limit=limit,
|
1499 |
+
use_trial=use_trial,
|
1500 |
+
use_rho=use_rho,
|
1501 |
+
use_pm1=use_pm1,
|
1502 |
+
verbose=verbose).items():
|
1503 |
+
f[p] += -e
|
1504 |
+
|
1505 |
+
if len(f) > 1 and 1 in f:
|
1506 |
+
del f[1]
|
1507 |
+
if not visual:
|
1508 |
+
return dict(f)
|
1509 |
+
else:
|
1510 |
+
if -1 in f:
|
1511 |
+
f.pop(-1)
|
1512 |
+
args = [S.NegativeOne]
|
1513 |
+
else:
|
1514 |
+
args = []
|
1515 |
+
args.extend([Pow(*i, evaluate=False)
|
1516 |
+
for i in sorted(f.items())])
|
1517 |
+
return Mul(*args, evaluate=False)
|
1518 |
+
|
1519 |
+
|
1520 |
+
|
1521 |
+
def primefactors(n, limit=None, verbose=False):
|
1522 |
+
"""Return a sorted list of n's prime factors, ignoring multiplicity
|
1523 |
+
and any composite factor that remains if the limit was set too low
|
1524 |
+
for complete factorization. Unlike factorint(), primefactors() does
|
1525 |
+
not return -1 or 0.
|
1526 |
+
|
1527 |
+
Examples
|
1528 |
+
========
|
1529 |
+
|
1530 |
+
>>> from sympy.ntheory import primefactors, factorint, isprime
|
1531 |
+
>>> primefactors(6)
|
1532 |
+
[2, 3]
|
1533 |
+
>>> primefactors(-5)
|
1534 |
+
[5]
|
1535 |
+
|
1536 |
+
>>> sorted(factorint(123456).items())
|
1537 |
+
[(2, 6), (3, 1), (643, 1)]
|
1538 |
+
>>> primefactors(123456)
|
1539 |
+
[2, 3, 643]
|
1540 |
+
|
1541 |
+
>>> sorted(factorint(10000000001, limit=200).items())
|
1542 |
+
[(101, 1), (99009901, 1)]
|
1543 |
+
>>> isprime(99009901)
|
1544 |
+
False
|
1545 |
+
>>> primefactors(10000000001, limit=300)
|
1546 |
+
[101]
|
1547 |
+
|
1548 |
+
See Also
|
1549 |
+
========
|
1550 |
+
|
1551 |
+
divisors
|
1552 |
+
"""
|
1553 |
+
n = int(n)
|
1554 |
+
factors = sorted(factorint(n, limit=limit, verbose=verbose).keys())
|
1555 |
+
s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
|
1556 |
+
if factors and isprime(factors[-1]):
|
1557 |
+
s += [factors[-1]]
|
1558 |
+
return s
|
1559 |
+
|
1560 |
+
|
1561 |
+
def _divisors(n, proper=False):
|
1562 |
+
"""Helper function for divisors which generates the divisors."""
|
1563 |
+
|
1564 |
+
factordict = factorint(n)
|
1565 |
+
ps = sorted(factordict.keys())
|
1566 |
+
|
1567 |
+
def rec_gen(n=0):
|
1568 |
+
if n == len(ps):
|
1569 |
+
yield 1
|
1570 |
+
else:
|
1571 |
+
pows = [1]
|
1572 |
+
for j in range(factordict[ps[n]]):
|
1573 |
+
pows.append(pows[-1] * ps[n])
|
1574 |
+
for q in rec_gen(n + 1):
|
1575 |
+
for p in pows:
|
1576 |
+
yield p * q
|
1577 |
+
|
1578 |
+
if proper:
|
1579 |
+
for p in rec_gen():
|
1580 |
+
if p != n:
|
1581 |
+
yield p
|
1582 |
+
else:
|
1583 |
+
yield from rec_gen()
|
1584 |
+
|
1585 |
+
|
1586 |
+
def divisors(n, generator=False, proper=False):
|
1587 |
+
r"""
|
1588 |
+
Return all divisors of n sorted from 1..n by default.
|
1589 |
+
If generator is ``True`` an unordered generator is returned.
|
1590 |
+
|
1591 |
+
The number of divisors of n can be quite large if there are many
|
1592 |
+
prime factors (counting repeated factors). If only the number of
|
1593 |
+
factors is desired use divisor_count(n).
|
1594 |
+
|
1595 |
+
Examples
|
1596 |
+
========
|
1597 |
+
|
1598 |
+
>>> from sympy import divisors, divisor_count
|
1599 |
+
>>> divisors(24)
|
1600 |
+
[1, 2, 3, 4, 6, 8, 12, 24]
|
1601 |
+
>>> divisor_count(24)
|
1602 |
+
8
|
1603 |
+
|
1604 |
+
>>> list(divisors(120, generator=True))
|
1605 |
+
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
|
1606 |
+
|
1607 |
+
Notes
|
1608 |
+
=====
|
1609 |
+
|
1610 |
+
This is a slightly modified version of Tim Peters referenced at:
|
1611 |
+
https://stackoverflow.com/questions/1010381/python-factorization
|
1612 |
+
|
1613 |
+
See Also
|
1614 |
+
========
|
1615 |
+
|
1616 |
+
primefactors, factorint, divisor_count
|
1617 |
+
"""
|
1618 |
+
|
1619 |
+
n = as_int(abs(n))
|
1620 |
+
if isprime(n):
|
1621 |
+
if proper:
|
1622 |
+
return [1]
|
1623 |
+
return [1, n]
|
1624 |
+
if n == 1:
|
1625 |
+
if proper:
|
1626 |
+
return []
|
1627 |
+
return [1]
|
1628 |
+
if n == 0:
|
1629 |
+
return []
|
1630 |
+
rv = _divisors(n, proper)
|
1631 |
+
if not generator:
|
1632 |
+
return sorted(rv)
|
1633 |
+
return rv
|
1634 |
+
|
1635 |
+
|
1636 |
+
def divisor_count(n, modulus=1, proper=False):
|
1637 |
+
"""
|
1638 |
+
Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
|
1639 |
+
those that are divisible by ``modulus`` are counted. If ``proper`` is True
|
1640 |
+
then the divisor of ``n`` will not be counted.
|
1641 |
+
|
1642 |
+
Examples
|
1643 |
+
========
|
1644 |
+
|
1645 |
+
>>> from sympy import divisor_count
|
1646 |
+
>>> divisor_count(6)
|
1647 |
+
4
|
1648 |
+
>>> divisor_count(6, 2)
|
1649 |
+
2
|
1650 |
+
>>> divisor_count(6, proper=True)
|
1651 |
+
3
|
1652 |
+
|
1653 |
+
See Also
|
1654 |
+
========
|
1655 |
+
|
1656 |
+
factorint, divisors, totient, proper_divisor_count
|
1657 |
+
|
1658 |
+
"""
|
1659 |
+
|
1660 |
+
if not modulus:
|
1661 |
+
return 0
|
1662 |
+
elif modulus != 1:
|
1663 |
+
n, r = divmod(n, modulus)
|
1664 |
+
if r:
|
1665 |
+
return 0
|
1666 |
+
if n == 0:
|
1667 |
+
return 0
|
1668 |
+
n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
|
1669 |
+
if n and proper:
|
1670 |
+
n -= 1
|
1671 |
+
return n
|
1672 |
+
|
1673 |
+
|
1674 |
+
def proper_divisors(n, generator=False):
|
1675 |
+
"""
|
1676 |
+
Return all divisors of n except n, sorted by default.
|
1677 |
+
If generator is ``True`` an unordered generator is returned.
|
1678 |
+
|
1679 |
+
Examples
|
1680 |
+
========
|
1681 |
+
|
1682 |
+
>>> from sympy import proper_divisors, proper_divisor_count
|
1683 |
+
>>> proper_divisors(24)
|
1684 |
+
[1, 2, 3, 4, 6, 8, 12]
|
1685 |
+
>>> proper_divisor_count(24)
|
1686 |
+
7
|
1687 |
+
>>> list(proper_divisors(120, generator=True))
|
1688 |
+
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
|
1689 |
+
|
1690 |
+
See Also
|
1691 |
+
========
|
1692 |
+
|
1693 |
+
factorint, divisors, proper_divisor_count
|
1694 |
+
|
1695 |
+
"""
|
1696 |
+
return divisors(n, generator=generator, proper=True)
|
1697 |
+
|
1698 |
+
|
1699 |
+
def proper_divisor_count(n, modulus=1):
|
1700 |
+
"""
|
1701 |
+
Return the number of proper divisors of ``n``.
|
1702 |
+
|
1703 |
+
Examples
|
1704 |
+
========
|
1705 |
+
|
1706 |
+
>>> from sympy import proper_divisor_count
|
1707 |
+
>>> proper_divisor_count(6)
|
1708 |
+
3
|
1709 |
+
>>> proper_divisor_count(6, modulus=2)
|
1710 |
+
1
|
1711 |
+
|
1712 |
+
See Also
|
1713 |
+
========
|
1714 |
+
|
1715 |
+
divisors, proper_divisors, divisor_count
|
1716 |
+
|
1717 |
+
"""
|
1718 |
+
return divisor_count(n, modulus=modulus, proper=True)
|
1719 |
+
|
1720 |
+
|
1721 |
+
def _udivisors(n):
|
1722 |
+
"""Helper function for udivisors which generates the unitary divisors."""
|
1723 |
+
|
1724 |
+
factorpows = [p**e for p, e in factorint(n).items()]
|
1725 |
+
for i in range(2**len(factorpows)):
|
1726 |
+
d, j, k = 1, i, 0
|
1727 |
+
while j:
|
1728 |
+
if (j & 1):
|
1729 |
+
d *= factorpows[k]
|
1730 |
+
j >>= 1
|
1731 |
+
k += 1
|
1732 |
+
yield d
|
1733 |
+
|
1734 |
+
|
1735 |
+
def udivisors(n, generator=False):
|
1736 |
+
r"""
|
1737 |
+
Return all unitary divisors of n sorted from 1..n by default.
|
1738 |
+
If generator is ``True`` an unordered generator is returned.
|
1739 |
+
|
1740 |
+
The number of unitary divisors of n can be quite large if there are many
|
1741 |
+
prime factors. If only the number of unitary divisors is desired use
|
1742 |
+
udivisor_count(n).
|
1743 |
+
|
1744 |
+
Examples
|
1745 |
+
========
|
1746 |
+
|
1747 |
+
>>> from sympy.ntheory.factor_ import udivisors, udivisor_count
|
1748 |
+
>>> udivisors(15)
|
1749 |
+
[1, 3, 5, 15]
|
1750 |
+
>>> udivisor_count(15)
|
1751 |
+
4
|
1752 |
+
|
1753 |
+
>>> sorted(udivisors(120, generator=True))
|
1754 |
+
[1, 3, 5, 8, 15, 24, 40, 120]
|
1755 |
+
|
1756 |
+
See Also
|
1757 |
+
========
|
1758 |
+
|
1759 |
+
primefactors, factorint, divisors, divisor_count, udivisor_count
|
1760 |
+
|
1761 |
+
References
|
1762 |
+
==========
|
1763 |
+
|
1764 |
+
.. [1] https://en.wikipedia.org/wiki/Unitary_divisor
|
1765 |
+
.. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
|
1766 |
+
|
1767 |
+
"""
|
1768 |
+
|
1769 |
+
n = as_int(abs(n))
|
1770 |
+
if isprime(n):
|
1771 |
+
return [1, n]
|
1772 |
+
if n == 1:
|
1773 |
+
return [1]
|
1774 |
+
if n == 0:
|
1775 |
+
return []
|
1776 |
+
rv = _udivisors(n)
|
1777 |
+
if not generator:
|
1778 |
+
return sorted(rv)
|
1779 |
+
return rv
|
1780 |
+
|
1781 |
+
|
1782 |
+
def udivisor_count(n):
|
1783 |
+
"""
|
1784 |
+
Return the number of unitary divisors of ``n``.
|
1785 |
+
|
1786 |
+
Parameters
|
1787 |
+
==========
|
1788 |
+
|
1789 |
+
n : integer
|
1790 |
+
|
1791 |
+
Examples
|
1792 |
+
========
|
1793 |
+
|
1794 |
+
>>> from sympy.ntheory.factor_ import udivisor_count
|
1795 |
+
>>> udivisor_count(120)
|
1796 |
+
8
|
1797 |
+
|
1798 |
+
See Also
|
1799 |
+
========
|
1800 |
+
|
1801 |
+
factorint, divisors, udivisors, divisor_count, totient
|
1802 |
+
|
1803 |
+
References
|
1804 |
+
==========
|
1805 |
+
|
1806 |
+
.. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
|
1807 |
+
|
1808 |
+
"""
|
1809 |
+
|
1810 |
+
if n == 0:
|
1811 |
+
return 0
|
1812 |
+
return 2**len([p for p in factorint(n) if p > 1])
|
1813 |
+
|
1814 |
+
|
1815 |
+
def _antidivisors(n):
|
1816 |
+
"""Helper function for antidivisors which generates the antidivisors."""
|
1817 |
+
|
1818 |
+
for d in _divisors(n):
|
1819 |
+
y = 2*d
|
1820 |
+
if n > y and n % y:
|
1821 |
+
yield y
|
1822 |
+
for d in _divisors(2*n-1):
|
1823 |
+
if n > d >= 2 and n % d:
|
1824 |
+
yield d
|
1825 |
+
for d in _divisors(2*n+1):
|
1826 |
+
if n > d >= 2 and n % d:
|
1827 |
+
yield d
|
1828 |
+
|
1829 |
+
|
1830 |
+
def antidivisors(n, generator=False):
|
1831 |
+
r"""
|
1832 |
+
Return all antidivisors of n sorted from 1..n by default.
|
1833 |
+
|
1834 |
+
Antidivisors [1]_ of n are numbers that do not divide n by the largest
|
1835 |
+
possible margin. If generator is True an unordered generator is returned.
|
1836 |
+
|
1837 |
+
Examples
|
1838 |
+
========
|
1839 |
+
|
1840 |
+
>>> from sympy.ntheory.factor_ import antidivisors
|
1841 |
+
>>> antidivisors(24)
|
1842 |
+
[7, 16]
|
1843 |
+
|
1844 |
+
>>> sorted(antidivisors(128, generator=True))
|
1845 |
+
[3, 5, 15, 17, 51, 85]
|
1846 |
+
|
1847 |
+
See Also
|
1848 |
+
========
|
1849 |
+
|
1850 |
+
primefactors, factorint, divisors, divisor_count, antidivisor_count
|
1851 |
+
|
1852 |
+
References
|
1853 |
+
==========
|
1854 |
+
|
1855 |
+
.. [1] definition is described in https://oeis.org/A066272/a066272a.html
|
1856 |
+
|
1857 |
+
"""
|
1858 |
+
|
1859 |
+
n = as_int(abs(n))
|
1860 |
+
if n <= 2:
|
1861 |
+
return []
|
1862 |
+
rv = _antidivisors(n)
|
1863 |
+
if not generator:
|
1864 |
+
return sorted(rv)
|
1865 |
+
return rv
|
1866 |
+
|
1867 |
+
|
1868 |
+
def antidivisor_count(n):
|
1869 |
+
"""
|
1870 |
+
Return the number of antidivisors [1]_ of ``n``.
|
1871 |
+
|
1872 |
+
Parameters
|
1873 |
+
==========
|
1874 |
+
|
1875 |
+
n : integer
|
1876 |
+
|
1877 |
+
Examples
|
1878 |
+
========
|
1879 |
+
|
1880 |
+
>>> from sympy.ntheory.factor_ import antidivisor_count
|
1881 |
+
>>> antidivisor_count(13)
|
1882 |
+
4
|
1883 |
+
>>> antidivisor_count(27)
|
1884 |
+
5
|
1885 |
+
|
1886 |
+
See Also
|
1887 |
+
========
|
1888 |
+
|
1889 |
+
factorint, divisors, antidivisors, divisor_count, totient
|
1890 |
+
|
1891 |
+
References
|
1892 |
+
==========
|
1893 |
+
|
1894 |
+
.. [1] formula from https://oeis.org/A066272
|
1895 |
+
|
1896 |
+
"""
|
1897 |
+
|
1898 |
+
n = as_int(abs(n))
|
1899 |
+
if n <= 2:
|
1900 |
+
return 0
|
1901 |
+
return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
|
1902 |
+
divisor_count(n) - divisor_count(n, 2) - 5
|
1903 |
+
|
1904 |
+
|
1905 |
+
class totient(Function):
|
1906 |
+
r"""
|
1907 |
+
Calculate the Euler totient function phi(n)
|
1908 |
+
|
1909 |
+
``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
|
1910 |
+
that are relatively prime to n.
|
1911 |
+
|
1912 |
+
Parameters
|
1913 |
+
==========
|
1914 |
+
|
1915 |
+
n : integer
|
1916 |
+
|
1917 |
+
Examples
|
1918 |
+
========
|
1919 |
+
|
1920 |
+
>>> from sympy.ntheory import totient
|
1921 |
+
>>> totient(1)
|
1922 |
+
1
|
1923 |
+
>>> totient(25)
|
1924 |
+
20
|
1925 |
+
>>> totient(45) == totient(5)*totient(9)
|
1926 |
+
True
|
1927 |
+
|
1928 |
+
See Also
|
1929 |
+
========
|
1930 |
+
|
1931 |
+
divisor_count
|
1932 |
+
|
1933 |
+
References
|
1934 |
+
==========
|
1935 |
+
|
1936 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
|
1937 |
+
.. [2] https://mathworld.wolfram.com/TotientFunction.html
|
1938 |
+
|
1939 |
+
"""
|
1940 |
+
@classmethod
|
1941 |
+
def eval(cls, n):
|
1942 |
+
if n.is_Integer:
|
1943 |
+
if n < 1:
|
1944 |
+
raise ValueError("n must be a positive integer")
|
1945 |
+
factors = factorint(n)
|
1946 |
+
return cls._from_factors(factors)
|
1947 |
+
elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False):
|
1948 |
+
raise ValueError("n must be a positive integer")
|
1949 |
+
|
1950 |
+
def _eval_is_integer(self):
|
1951 |
+
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
|
1952 |
+
|
1953 |
+
@classmethod
|
1954 |
+
def _from_distinct_primes(self, *args):
|
1955 |
+
"""Subroutine to compute totient from the list of assumed
|
1956 |
+
distinct primes
|
1957 |
+
|
1958 |
+
Examples
|
1959 |
+
========
|
1960 |
+
|
1961 |
+
>>> from sympy.ntheory.factor_ import totient
|
1962 |
+
>>> totient._from_distinct_primes(5, 7)
|
1963 |
+
24
|
1964 |
+
"""
|
1965 |
+
return reduce(lambda i, j: i * (j-1), args, 1)
|
1966 |
+
|
1967 |
+
@classmethod
|
1968 |
+
def _from_factors(self, factors):
|
1969 |
+
"""Subroutine to compute totient from already-computed factors
|
1970 |
+
|
1971 |
+
Examples
|
1972 |
+
========
|
1973 |
+
|
1974 |
+
>>> from sympy.ntheory.factor_ import totient
|
1975 |
+
>>> totient._from_factors({5: 2})
|
1976 |
+
20
|
1977 |
+
"""
|
1978 |
+
t = 1
|
1979 |
+
for p, k in factors.items():
|
1980 |
+
t *= (p - 1) * p**(k - 1)
|
1981 |
+
return t
|
1982 |
+
|
1983 |
+
|
1984 |
+
class reduced_totient(Function):
|
1985 |
+
r"""
|
1986 |
+
Calculate the Carmichael reduced totient function lambda(n)
|
1987 |
+
|
1988 |
+
``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
|
1989 |
+
`k^m \equiv 1 \mod n` for all k relatively prime to n.
|
1990 |
+
|
1991 |
+
Examples
|
1992 |
+
========
|
1993 |
+
|
1994 |
+
>>> from sympy.ntheory import reduced_totient
|
1995 |
+
>>> reduced_totient(1)
|
1996 |
+
1
|
1997 |
+
>>> reduced_totient(8)
|
1998 |
+
2
|
1999 |
+
>>> reduced_totient(30)
|
2000 |
+
4
|
2001 |
+
|
2002 |
+
See Also
|
2003 |
+
========
|
2004 |
+
|
2005 |
+
totient
|
2006 |
+
|
2007 |
+
References
|
2008 |
+
==========
|
2009 |
+
|
2010 |
+
.. [1] https://en.wikipedia.org/wiki/Carmichael_function
|
2011 |
+
.. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
|
2012 |
+
|
2013 |
+
"""
|
2014 |
+
@classmethod
|
2015 |
+
def eval(cls, n):
|
2016 |
+
if n.is_Integer:
|
2017 |
+
if n < 1:
|
2018 |
+
raise ValueError("n must be a positive integer")
|
2019 |
+
factors = factorint(n)
|
2020 |
+
return cls._from_factors(factors)
|
2021 |
+
|
2022 |
+
@classmethod
|
2023 |
+
def _from_factors(self, factors):
|
2024 |
+
"""Subroutine to compute totient from already-computed factors
|
2025 |
+
"""
|
2026 |
+
t = 1
|
2027 |
+
for p, k in factors.items():
|
2028 |
+
if p == 2 and k > 2:
|
2029 |
+
t = ilcm(t, 2**(k - 2))
|
2030 |
+
else:
|
2031 |
+
t = ilcm(t, (p - 1) * p**(k - 1))
|
2032 |
+
return t
|
2033 |
+
|
2034 |
+
@classmethod
|
2035 |
+
def _from_distinct_primes(self, *args):
|
2036 |
+
"""Subroutine to compute totient from the list of assumed
|
2037 |
+
distinct primes
|
2038 |
+
"""
|
2039 |
+
args = [p - 1 for p in args]
|
2040 |
+
return ilcm(*args)
|
2041 |
+
|
2042 |
+
def _eval_is_integer(self):
|
2043 |
+
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
|
2044 |
+
|
2045 |
+
|
2046 |
+
class divisor_sigma(Function):
|
2047 |
+
r"""
|
2048 |
+
Calculate the divisor function `\sigma_k(n)` for positive integer n
|
2049 |
+
|
2050 |
+
``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
|
2051 |
+
|
2052 |
+
If n's prime factorization is:
|
2053 |
+
|
2054 |
+
.. math ::
|
2055 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
2056 |
+
|
2057 |
+
then
|
2058 |
+
|
2059 |
+
.. math ::
|
2060 |
+
\sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
|
2061 |
+
+ p_i^{m_ik}).
|
2062 |
+
|
2063 |
+
Parameters
|
2064 |
+
==========
|
2065 |
+
|
2066 |
+
n : integer
|
2067 |
+
|
2068 |
+
k : integer, optional
|
2069 |
+
power of divisors in the sum
|
2070 |
+
|
2071 |
+
for k = 0, 1:
|
2072 |
+
``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
|
2073 |
+
``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
|
2074 |
+
|
2075 |
+
Default for k is 1.
|
2076 |
+
|
2077 |
+
Examples
|
2078 |
+
========
|
2079 |
+
|
2080 |
+
>>> from sympy.ntheory import divisor_sigma
|
2081 |
+
>>> divisor_sigma(18, 0)
|
2082 |
+
6
|
2083 |
+
>>> divisor_sigma(39, 1)
|
2084 |
+
56
|
2085 |
+
>>> divisor_sigma(12, 2)
|
2086 |
+
210
|
2087 |
+
>>> divisor_sigma(37)
|
2088 |
+
38
|
2089 |
+
|
2090 |
+
See Also
|
2091 |
+
========
|
2092 |
+
|
2093 |
+
divisor_count, totient, divisors, factorint
|
2094 |
+
|
2095 |
+
References
|
2096 |
+
==========
|
2097 |
+
|
2098 |
+
.. [1] https://en.wikipedia.org/wiki/Divisor_function
|
2099 |
+
|
2100 |
+
"""
|
2101 |
+
|
2102 |
+
@classmethod
|
2103 |
+
def eval(cls, n, k=S.One):
|
2104 |
+
k = sympify(k)
|
2105 |
+
|
2106 |
+
if n.is_prime:
|
2107 |
+
return 1 + n**k
|
2108 |
+
|
2109 |
+
if n.is_Integer:
|
2110 |
+
if n <= 0:
|
2111 |
+
raise ValueError("n must be a positive integer")
|
2112 |
+
elif k.is_Integer:
|
2113 |
+
k = int(k)
|
2114 |
+
return Integer(math.prod(
|
2115 |
+
(p**(k*(e + 1)) - 1)//(p**k - 1) if k != 0
|
2116 |
+
else e + 1 for p, e in factorint(n).items()))
|
2117 |
+
else:
|
2118 |
+
return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0
|
2119 |
+
else e + 1 for p, e in factorint(n).items()])
|
2120 |
+
|
2121 |
+
if n.is_integer: # symbolic case
|
2122 |
+
args = []
|
2123 |
+
for p, e in (_.as_base_exp() for _ in Mul.make_args(n)):
|
2124 |
+
if p.is_prime and e.is_positive:
|
2125 |
+
args.append((p**(k*(e + 1)) - 1)/(p**k - 1) if
|
2126 |
+
k != 0 else e + 1)
|
2127 |
+
else:
|
2128 |
+
return
|
2129 |
+
return Mul(*args)
|
2130 |
+
|
2131 |
+
|
2132 |
+
def core(n, t=2):
|
2133 |
+
r"""
|
2134 |
+
Calculate core(n, t) = `core_t(n)` of a positive integer n
|
2135 |
+
|
2136 |
+
``core_2(n)`` is equal to the squarefree part of n
|
2137 |
+
|
2138 |
+
If n's prime factorization is:
|
2139 |
+
|
2140 |
+
.. math ::
|
2141 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
2142 |
+
|
2143 |
+
then
|
2144 |
+
|
2145 |
+
.. math ::
|
2146 |
+
core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
|
2147 |
+
|
2148 |
+
Parameters
|
2149 |
+
==========
|
2150 |
+
|
2151 |
+
n : integer
|
2152 |
+
|
2153 |
+
t : integer
|
2154 |
+
core(n, t) calculates the t-th power free part of n
|
2155 |
+
|
2156 |
+
``core(n, 2)`` is the squarefree part of ``n``
|
2157 |
+
``core(n, 3)`` is the cubefree part of ``n``
|
2158 |
+
|
2159 |
+
Default for t is 2.
|
2160 |
+
|
2161 |
+
Examples
|
2162 |
+
========
|
2163 |
+
|
2164 |
+
>>> from sympy.ntheory.factor_ import core
|
2165 |
+
>>> core(24, 2)
|
2166 |
+
6
|
2167 |
+
>>> core(9424, 3)
|
2168 |
+
1178
|
2169 |
+
>>> core(379238)
|
2170 |
+
379238
|
2171 |
+
>>> core(15**11, 10)
|
2172 |
+
15
|
2173 |
+
|
2174 |
+
See Also
|
2175 |
+
========
|
2176 |
+
|
2177 |
+
factorint, sympy.solvers.diophantine.diophantine.square_factor
|
2178 |
+
|
2179 |
+
References
|
2180 |
+
==========
|
2181 |
+
|
2182 |
+
.. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
|
2183 |
+
|
2184 |
+
"""
|
2185 |
+
|
2186 |
+
n = as_int(n)
|
2187 |
+
t = as_int(t)
|
2188 |
+
if n <= 0:
|
2189 |
+
raise ValueError("n must be a positive integer")
|
2190 |
+
elif t <= 1:
|
2191 |
+
raise ValueError("t must be >= 2")
|
2192 |
+
else:
|
2193 |
+
y = 1
|
2194 |
+
for p, e in factorint(n).items():
|
2195 |
+
y *= p**(e % t)
|
2196 |
+
return y
|
2197 |
+
|
2198 |
+
|
2199 |
+
class udivisor_sigma(Function):
|
2200 |
+
r"""
|
2201 |
+
Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
|
2202 |
+
|
2203 |
+
``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
|
2204 |
+
|
2205 |
+
If n's prime factorization is:
|
2206 |
+
|
2207 |
+
.. math ::
|
2208 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
2209 |
+
|
2210 |
+
then
|
2211 |
+
|
2212 |
+
.. math ::
|
2213 |
+
\sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
|
2214 |
+
|
2215 |
+
Parameters
|
2216 |
+
==========
|
2217 |
+
|
2218 |
+
k : power of divisors in the sum
|
2219 |
+
|
2220 |
+
for k = 0, 1:
|
2221 |
+
``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
|
2222 |
+
``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
|
2223 |
+
|
2224 |
+
Default for k is 1.
|
2225 |
+
|
2226 |
+
Examples
|
2227 |
+
========
|
2228 |
+
|
2229 |
+
>>> from sympy.ntheory.factor_ import udivisor_sigma
|
2230 |
+
>>> udivisor_sigma(18, 0)
|
2231 |
+
4
|
2232 |
+
>>> udivisor_sigma(74, 1)
|
2233 |
+
114
|
2234 |
+
>>> udivisor_sigma(36, 3)
|
2235 |
+
47450
|
2236 |
+
>>> udivisor_sigma(111)
|
2237 |
+
152
|
2238 |
+
|
2239 |
+
See Also
|
2240 |
+
========
|
2241 |
+
|
2242 |
+
divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
|
2243 |
+
factorint
|
2244 |
+
|
2245 |
+
References
|
2246 |
+
==========
|
2247 |
+
|
2248 |
+
.. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
|
2249 |
+
|
2250 |
+
"""
|
2251 |
+
|
2252 |
+
@classmethod
|
2253 |
+
def eval(cls, n, k=S.One):
|
2254 |
+
k = sympify(k)
|
2255 |
+
if n.is_prime:
|
2256 |
+
return 1 + n**k
|
2257 |
+
if n.is_Integer:
|
2258 |
+
if n <= 0:
|
2259 |
+
raise ValueError("n must be a positive integer")
|
2260 |
+
else:
|
2261 |
+
return Mul(*[1+p**(k*e) for p, e in factorint(n).items()])
|
2262 |
+
|
2263 |
+
|
2264 |
+
class primenu(Function):
|
2265 |
+
r"""
|
2266 |
+
Calculate the number of distinct prime factors for a positive integer n.
|
2267 |
+
|
2268 |
+
If n's prime factorization is:
|
2269 |
+
|
2270 |
+
.. math ::
|
2271 |
+
n = \prod_{i=1}^k p_i^{m_i},
|
2272 |
+
|
2273 |
+
then ``primenu(n)`` or `\nu(n)` is:
|
2274 |
+
|
2275 |
+
.. math ::
|
2276 |
+
\nu(n) = k.
|
2277 |
+
|
2278 |
+
Examples
|
2279 |
+
========
|
2280 |
+
|
2281 |
+
>>> from sympy.ntheory.factor_ import primenu
|
2282 |
+
>>> primenu(1)
|
2283 |
+
0
|
2284 |
+
>>> primenu(30)
|
2285 |
+
3
|
2286 |
+
|
2287 |
+
See Also
|
2288 |
+
========
|
2289 |
+
|
2290 |
+
factorint
|
2291 |
+
|
2292 |
+
References
|
2293 |
+
==========
|
2294 |
+
|
2295 |
+
.. [1] https://mathworld.wolfram.com/PrimeFactor.html
|
2296 |
+
|
2297 |
+
"""
|
2298 |
+
|
2299 |
+
@classmethod
|
2300 |
+
def eval(cls, n):
|
2301 |
+
if n.is_Integer:
|
2302 |
+
if n <= 0:
|
2303 |
+
raise ValueError("n must be a positive integer")
|
2304 |
+
else:
|
2305 |
+
return len(factorint(n).keys())
|
2306 |
+
|
2307 |
+
|
2308 |
+
class primeomega(Function):
|
2309 |
+
r"""
|
2310 |
+
Calculate the number of prime factors counting multiplicities for a
|
2311 |
+
positive integer n.
|
2312 |
+
|
2313 |
+
If n's prime factorization is:
|
2314 |
+
|
2315 |
+
.. math ::
|
2316 |
+
n = \prod_{i=1}^k p_i^{m_i},
|
2317 |
+
|
2318 |
+
then ``primeomega(n)`` or `\Omega(n)` is:
|
2319 |
+
|
2320 |
+
.. math ::
|
2321 |
+
\Omega(n) = \sum_{i=1}^k m_i.
|
2322 |
+
|
2323 |
+
Examples
|
2324 |
+
========
|
2325 |
+
|
2326 |
+
>>> from sympy.ntheory.factor_ import primeomega
|
2327 |
+
>>> primeomega(1)
|
2328 |
+
0
|
2329 |
+
>>> primeomega(20)
|
2330 |
+
3
|
2331 |
+
|
2332 |
+
See Also
|
2333 |
+
========
|
2334 |
+
|
2335 |
+
factorint
|
2336 |
+
|
2337 |
+
References
|
2338 |
+
==========
|
2339 |
+
|
2340 |
+
.. [1] https://mathworld.wolfram.com/PrimeFactor.html
|
2341 |
+
|
2342 |
+
"""
|
2343 |
+
|
2344 |
+
@classmethod
|
2345 |
+
def eval(cls, n):
|
2346 |
+
if n.is_Integer:
|
2347 |
+
if n <= 0:
|
2348 |
+
raise ValueError("n must be a positive integer")
|
2349 |
+
else:
|
2350 |
+
return sum(factorint(n).values())
|
2351 |
+
|
2352 |
+
|
2353 |
+
def mersenne_prime_exponent(nth):
|
2354 |
+
"""Returns the exponent ``i`` for the nth Mersenne prime (which
|
2355 |
+
has the form `2^i - 1`).
|
2356 |
+
|
2357 |
+
Examples
|
2358 |
+
========
|
2359 |
+
|
2360 |
+
>>> from sympy.ntheory.factor_ import mersenne_prime_exponent
|
2361 |
+
>>> mersenne_prime_exponent(1)
|
2362 |
+
2
|
2363 |
+
>>> mersenne_prime_exponent(20)
|
2364 |
+
4423
|
2365 |
+
"""
|
2366 |
+
n = as_int(nth)
|
2367 |
+
if n < 1:
|
2368 |
+
raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
|
2369 |
+
if n > 51:
|
2370 |
+
raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
|
2371 |
+
return MERSENNE_PRIME_EXPONENTS[n - 1]
|
2372 |
+
|
2373 |
+
|
2374 |
+
def is_perfect(n):
|
2375 |
+
"""Returns True if ``n`` is a perfect number, else False.
|
2376 |
+
|
2377 |
+
A perfect number is equal to the sum of its positive, proper divisors.
|
2378 |
+
|
2379 |
+
Examples
|
2380 |
+
========
|
2381 |
+
|
2382 |
+
>>> from sympy.ntheory.factor_ import is_perfect, divisors, divisor_sigma
|
2383 |
+
>>> is_perfect(20)
|
2384 |
+
False
|
2385 |
+
>>> is_perfect(6)
|
2386 |
+
True
|
2387 |
+
>>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
|
2388 |
+
True
|
2389 |
+
|
2390 |
+
References
|
2391 |
+
==========
|
2392 |
+
|
2393 |
+
.. [1] https://mathworld.wolfram.com/PerfectNumber.html
|
2394 |
+
.. [2] https://en.wikipedia.org/wiki/Perfect_number
|
2395 |
+
|
2396 |
+
"""
|
2397 |
+
|
2398 |
+
n = as_int(n)
|
2399 |
+
if _isperfect(n):
|
2400 |
+
return True
|
2401 |
+
|
2402 |
+
# all perfect numbers for Mersenne primes with exponents
|
2403 |
+
# less than or equal to 43112609 are known
|
2404 |
+
iknow = MERSENNE_PRIME_EXPONENTS.index(43112609)
|
2405 |
+
if iknow <= len(PERFECT) - 1 and n <= PERFECT[iknow]:
|
2406 |
+
# there may be gaps between this and larger known values
|
2407 |
+
# so only conclude in the range for which all values
|
2408 |
+
# are known
|
2409 |
+
return False
|
2410 |
+
if n%2 == 0:
|
2411 |
+
last2 = n % 100
|
2412 |
+
if last2 != 28 and last2 % 10 != 6:
|
2413 |
+
return False
|
2414 |
+
r, b = integer_nthroot(1 + 8*n, 2)
|
2415 |
+
if not b:
|
2416 |
+
return False
|
2417 |
+
m, x = divmod(1 + r, 4)
|
2418 |
+
if x:
|
2419 |
+
return False
|
2420 |
+
e, b = integer_log(m, 2)
|
2421 |
+
if not b:
|
2422 |
+
return False
|
2423 |
+
else:
|
2424 |
+
if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/
|
2425 |
+
return False
|
2426 |
+
if n % 105 == 0: # not divis by 105
|
2427 |
+
return False
|
2428 |
+
if not any(n%m == r for m, r in [(12, 1), (468, 117), (324, 81)]):
|
2429 |
+
return False
|
2430 |
+
# there are many criteria that the factor structure of n
|
2431 |
+
# must meet; since we will have to factor it to test the
|
2432 |
+
# structure we will have the factors and can then check
|
2433 |
+
# to see whether it is a perfect number or not. So we
|
2434 |
+
# skip the structure checks and go straight to the final
|
2435 |
+
# test below.
|
2436 |
+
rv = divisor_sigma(n) - n
|
2437 |
+
if rv == n:
|
2438 |
+
if n%2 == 0:
|
2439 |
+
raise ValueError(filldedent('''
|
2440 |
+
This even number is perfect and is associated with a
|
2441 |
+
Mersenne Prime, 2^%s - 1. It should be
|
2442 |
+
added to SymPy.''' % (e + 1)))
|
2443 |
+
else:
|
2444 |
+
raise ValueError(filldedent('''In 1888, Sylvester stated: "
|
2445 |
+
...a prolonged meditation on the subject has satisfied
|
2446 |
+
me that the existence of any one such [odd perfect number]
|
2447 |
+
-- its escape, so to say, from the complex web of conditions
|
2448 |
+
which hem it in on all sides -- would be little short of a
|
2449 |
+
miracle." I guess SymPy just found that miracle and it
|
2450 |
+
factors like this: %s''' % factorint(n)))
|
2451 |
+
|
2452 |
+
|
2453 |
+
def is_mersenne_prime(n):
|
2454 |
+
"""Returns True if ``n`` is a Mersenne prime, else False.
|
2455 |
+
|
2456 |
+
A Mersenne prime is a prime number having the form `2^i - 1`.
|
2457 |
+
|
2458 |
+
Examples
|
2459 |
+
========
|
2460 |
+
|
2461 |
+
>>> from sympy.ntheory.factor_ import is_mersenne_prime
|
2462 |
+
>>> is_mersenne_prime(6)
|
2463 |
+
False
|
2464 |
+
>>> is_mersenne_prime(127)
|
2465 |
+
True
|
2466 |
+
|
2467 |
+
References
|
2468 |
+
==========
|
2469 |
+
|
2470 |
+
.. [1] https://mathworld.wolfram.com/MersennePrime.html
|
2471 |
+
|
2472 |
+
"""
|
2473 |
+
|
2474 |
+
n = as_int(n)
|
2475 |
+
if _ismersenneprime(n):
|
2476 |
+
return True
|
2477 |
+
if not isprime(n):
|
2478 |
+
return False
|
2479 |
+
r, b = integer_log(n + 1, 2)
|
2480 |
+
if not b:
|
2481 |
+
return False
|
2482 |
+
raise ValueError(filldedent('''
|
2483 |
+
This Mersenne Prime, 2^%s - 1, should
|
2484 |
+
be added to SymPy's known values.''' % r))
|
2485 |
+
|
2486 |
+
|
2487 |
+
def abundance(n):
|
2488 |
+
"""Returns the difference between the sum of the positive
|
2489 |
+
proper divisors of a number and the number.
|
2490 |
+
|
2491 |
+
Examples
|
2492 |
+
========
|
2493 |
+
|
2494 |
+
>>> from sympy.ntheory import abundance, is_perfect, is_abundant
|
2495 |
+
>>> abundance(6)
|
2496 |
+
0
|
2497 |
+
>>> is_perfect(6)
|
2498 |
+
True
|
2499 |
+
>>> abundance(10)
|
2500 |
+
-2
|
2501 |
+
>>> is_abundant(10)
|
2502 |
+
False
|
2503 |
+
"""
|
2504 |
+
return divisor_sigma(n, 1) - 2 * n
|
2505 |
+
|
2506 |
+
|
2507 |
+
def is_abundant(n):
|
2508 |
+
"""Returns True if ``n`` is an abundant number, else False.
|
2509 |
+
|
2510 |
+
A abundant number is smaller than the sum of its positive proper divisors.
|
2511 |
+
|
2512 |
+
Examples
|
2513 |
+
========
|
2514 |
+
|
2515 |
+
>>> from sympy.ntheory.factor_ import is_abundant
|
2516 |
+
>>> is_abundant(20)
|
2517 |
+
True
|
2518 |
+
>>> is_abundant(15)
|
2519 |
+
False
|
2520 |
+
|
2521 |
+
References
|
2522 |
+
==========
|
2523 |
+
|
2524 |
+
.. [1] https://mathworld.wolfram.com/AbundantNumber.html
|
2525 |
+
|
2526 |
+
"""
|
2527 |
+
n = as_int(n)
|
2528 |
+
if is_perfect(n):
|
2529 |
+
return False
|
2530 |
+
return n % 6 == 0 or bool(abundance(n) > 0)
|
2531 |
+
|
2532 |
+
|
2533 |
+
def is_deficient(n):
|
2534 |
+
"""Returns True if ``n`` is a deficient number, else False.
|
2535 |
+
|
2536 |
+
A deficient number is greater than the sum of its positive proper divisors.
|
2537 |
+
|
2538 |
+
Examples
|
2539 |
+
========
|
2540 |
+
|
2541 |
+
>>> from sympy.ntheory.factor_ import is_deficient
|
2542 |
+
>>> is_deficient(20)
|
2543 |
+
False
|
2544 |
+
>>> is_deficient(15)
|
2545 |
+
True
|
2546 |
+
|
2547 |
+
References
|
2548 |
+
==========
|
2549 |
+
|
2550 |
+
.. [1] https://mathworld.wolfram.com/DeficientNumber.html
|
2551 |
+
|
2552 |
+
"""
|
2553 |
+
n = as_int(n)
|
2554 |
+
if is_perfect(n):
|
2555 |
+
return False
|
2556 |
+
return bool(abundance(n) < 0)
|
2557 |
+
|
2558 |
+
|
2559 |
+
def is_amicable(m, n):
|
2560 |
+
"""Returns True if the numbers `m` and `n` are "amicable", else False.
|
2561 |
+
|
2562 |
+
Amicable numbers are two different numbers so related that the sum
|
2563 |
+
of the proper divisors of each is equal to that of the other.
|
2564 |
+
|
2565 |
+
Examples
|
2566 |
+
========
|
2567 |
+
|
2568 |
+
>>> from sympy.ntheory.factor_ import is_amicable, divisor_sigma
|
2569 |
+
>>> is_amicable(220, 284)
|
2570 |
+
True
|
2571 |
+
>>> divisor_sigma(220) == divisor_sigma(284)
|
2572 |
+
True
|
2573 |
+
|
2574 |
+
References
|
2575 |
+
==========
|
2576 |
+
|
2577 |
+
.. [1] https://en.wikipedia.org/wiki/Amicable_numbers
|
2578 |
+
|
2579 |
+
"""
|
2580 |
+
if m == n:
|
2581 |
+
return False
|
2582 |
+
a, b = (divisor_sigma(i) for i in (m, n))
|
2583 |
+
return a == b == (m + n)
|
2584 |
+
|
2585 |
+
|
2586 |
+
def dra(n, b):
|
2587 |
+
"""
|
2588 |
+
Returns the additive digital root of a natural number ``n`` in base ``b``
|
2589 |
+
which is a single digit value obtained by an iterative process of summing
|
2590 |
+
digits, on each iteration using the result from the previous iteration to
|
2591 |
+
compute a digit sum.
|
2592 |
+
|
2593 |
+
Examples
|
2594 |
+
========
|
2595 |
+
|
2596 |
+
>>> from sympy.ntheory.factor_ import dra
|
2597 |
+
>>> dra(3110, 12)
|
2598 |
+
8
|
2599 |
+
|
2600 |
+
References
|
2601 |
+
==========
|
2602 |
+
|
2603 |
+
.. [1] https://en.wikipedia.org/wiki/Digital_root
|
2604 |
+
|
2605 |
+
"""
|
2606 |
+
|
2607 |
+
num = abs(as_int(n))
|
2608 |
+
b = as_int(b)
|
2609 |
+
if b <= 1:
|
2610 |
+
raise ValueError("Base should be an integer greater than 1")
|
2611 |
+
|
2612 |
+
if num == 0:
|
2613 |
+
return 0
|
2614 |
+
|
2615 |
+
return (1 + (num - 1) % (b - 1))
|
2616 |
+
|
2617 |
+
|
2618 |
+
def drm(n, b):
|
2619 |
+
"""
|
2620 |
+
Returns the multiplicative digital root of a natural number ``n`` in a given
|
2621 |
+
base ``b`` which is a single digit value obtained by an iterative process of
|
2622 |
+
multiplying digits, on each iteration using the result from the previous
|
2623 |
+
iteration to compute the digit multiplication.
|
2624 |
+
|
2625 |
+
Examples
|
2626 |
+
========
|
2627 |
+
|
2628 |
+
>>> from sympy.ntheory.factor_ import drm
|
2629 |
+
>>> drm(9876, 10)
|
2630 |
+
0
|
2631 |
+
|
2632 |
+
>>> drm(49, 10)
|
2633 |
+
8
|
2634 |
+
|
2635 |
+
References
|
2636 |
+
==========
|
2637 |
+
|
2638 |
+
.. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
|
2639 |
+
|
2640 |
+
"""
|
2641 |
+
|
2642 |
+
n = abs(as_int(n))
|
2643 |
+
b = as_int(b)
|
2644 |
+
if b <= 1:
|
2645 |
+
raise ValueError("Base should be an integer greater than 1")
|
2646 |
+
while n > b:
|
2647 |
+
mul = 1
|
2648 |
+
while n > 1:
|
2649 |
+
n, r = divmod(n, b)
|
2650 |
+
if r == 0:
|
2651 |
+
return 0
|
2652 |
+
mul *= r
|
2653 |
+
n = mul
|
2654 |
+
return n
|
venv/lib/python3.10/site-packages/sympy/ntheory/generate.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Generating and counting primes.
|
3 |
+
|
4 |
+
"""
|
5 |
+
|
6 |
+
import random
|
7 |
+
from bisect import bisect
|
8 |
+
from itertools import count
|
9 |
+
# Using arrays for sieving instead of lists greatly reduces
|
10 |
+
# memory consumption
|
11 |
+
from array import array as _array
|
12 |
+
|
13 |
+
from sympy.core.function import Function
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
from .primetest import isprime
|
16 |
+
from sympy.utilities.misc import as_int
|
17 |
+
|
18 |
+
|
19 |
+
def _azeros(n):
|
20 |
+
return _array('l', [0]*n)
|
21 |
+
|
22 |
+
|
23 |
+
def _aset(*v):
|
24 |
+
return _array('l', v)
|
25 |
+
|
26 |
+
|
27 |
+
def _arange(a, b):
|
28 |
+
return _array('l', range(a, b))
|
29 |
+
|
30 |
+
|
31 |
+
def _as_int_ceiling(a):
|
32 |
+
""" Wrapping ceiling in as_int will raise an error if there was a problem
|
33 |
+
determining whether the expression was exactly an integer or not."""
|
34 |
+
from sympy.functions.elementary.integers import ceiling
|
35 |
+
return as_int(ceiling(a))
|
36 |
+
|
37 |
+
|
38 |
+
class Sieve:
|
39 |
+
"""An infinite list of prime numbers, implemented as a dynamically
|
40 |
+
growing sieve of Eratosthenes. When a lookup is requested involving
|
41 |
+
an odd number that has not been sieved, the sieve is automatically
|
42 |
+
extended up to that number.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
========
|
46 |
+
|
47 |
+
>>> from sympy import sieve
|
48 |
+
>>> sieve._reset() # this line for doctest only
|
49 |
+
>>> 25 in sieve
|
50 |
+
False
|
51 |
+
>>> sieve._list
|
52 |
+
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
|
53 |
+
"""
|
54 |
+
|
55 |
+
# data shared (and updated) by all Sieve instances
|
56 |
+
def __init__(self):
|
57 |
+
self._n = 6
|
58 |
+
self._list = _aset(2, 3, 5, 7, 11, 13) # primes
|
59 |
+
self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient
|
60 |
+
self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius
|
61 |
+
assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
|
62 |
+
|
63 |
+
def __repr__(self):
|
64 |
+
return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
|
65 |
+
"%s sieve (%i): %i, %i, %i, ... %i, %i\n"
|
66 |
+
"%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
|
67 |
+
'prime', len(self._list),
|
68 |
+
self._list[0], self._list[1], self._list[2],
|
69 |
+
self._list[-2], self._list[-1],
|
70 |
+
'totient', len(self._tlist),
|
71 |
+
self._tlist[0], self._tlist[1],
|
72 |
+
self._tlist[2], self._tlist[-2], self._tlist[-1],
|
73 |
+
'mobius', len(self._mlist),
|
74 |
+
self._mlist[0], self._mlist[1],
|
75 |
+
self._mlist[2], self._mlist[-2], self._mlist[-1])
|
76 |
+
|
77 |
+
def _reset(self, prime=None, totient=None, mobius=None):
|
78 |
+
"""Reset all caches (default). To reset one or more set the
|
79 |
+
desired keyword to True."""
|
80 |
+
if all(i is None for i in (prime, totient, mobius)):
|
81 |
+
prime = totient = mobius = True
|
82 |
+
if prime:
|
83 |
+
self._list = self._list[:self._n]
|
84 |
+
if totient:
|
85 |
+
self._tlist = self._tlist[:self._n]
|
86 |
+
if mobius:
|
87 |
+
self._mlist = self._mlist[:self._n]
|
88 |
+
|
89 |
+
def extend(self, n):
|
90 |
+
"""Grow the sieve to cover all primes <= n (a real number).
|
91 |
+
|
92 |
+
Examples
|
93 |
+
========
|
94 |
+
|
95 |
+
>>> from sympy import sieve
|
96 |
+
>>> sieve._reset() # this line for doctest only
|
97 |
+
>>> sieve.extend(30)
|
98 |
+
>>> sieve[10] == 29
|
99 |
+
True
|
100 |
+
"""
|
101 |
+
n = int(n)
|
102 |
+
if n <= self._list[-1]:
|
103 |
+
return
|
104 |
+
|
105 |
+
# We need to sieve against all bases up to sqrt(n).
|
106 |
+
# This is a recursive call that will do nothing if there are enough
|
107 |
+
# known bases already.
|
108 |
+
maxbase = int(n**0.5) + 1
|
109 |
+
self.extend(maxbase)
|
110 |
+
|
111 |
+
# Create a new sieve starting from sqrt(n)
|
112 |
+
begin = self._list[-1] + 1
|
113 |
+
newsieve = _arange(begin, n + 1)
|
114 |
+
|
115 |
+
# Now eliminate all multiples of primes in [2, sqrt(n)]
|
116 |
+
for p in self.primerange(maxbase):
|
117 |
+
# Start counting at a multiple of p, offsetting
|
118 |
+
# the index to account for the new sieve's base index
|
119 |
+
startindex = (-begin) % p
|
120 |
+
for i in range(startindex, len(newsieve), p):
|
121 |
+
newsieve[i] = 0
|
122 |
+
|
123 |
+
# Merge the sieves
|
124 |
+
self._list += _array('l', [x for x in newsieve if x])
|
125 |
+
|
126 |
+
def extend_to_no(self, i):
|
127 |
+
"""Extend to include the ith prime number.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
==========
|
131 |
+
|
132 |
+
i : integer
|
133 |
+
|
134 |
+
Examples
|
135 |
+
========
|
136 |
+
|
137 |
+
>>> from sympy import sieve
|
138 |
+
>>> sieve._reset() # this line for doctest only
|
139 |
+
>>> sieve.extend_to_no(9)
|
140 |
+
>>> sieve._list
|
141 |
+
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
|
142 |
+
|
143 |
+
Notes
|
144 |
+
=====
|
145 |
+
|
146 |
+
The list is extended by 50% if it is too short, so it is
|
147 |
+
likely that it will be longer than requested.
|
148 |
+
"""
|
149 |
+
i = as_int(i)
|
150 |
+
while len(self._list) < i:
|
151 |
+
self.extend(int(self._list[-1] * 1.5))
|
152 |
+
|
153 |
+
def primerange(self, a, b=None):
|
154 |
+
"""Generate all prime numbers in the range [2, a) or [a, b).
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
>>> from sympy import sieve, prime
|
160 |
+
|
161 |
+
All primes less than 19:
|
162 |
+
|
163 |
+
>>> print([i for i in sieve.primerange(19)])
|
164 |
+
[2, 3, 5, 7, 11, 13, 17]
|
165 |
+
|
166 |
+
All primes greater than or equal to 7 and less than 19:
|
167 |
+
|
168 |
+
>>> print([i for i in sieve.primerange(7, 19)])
|
169 |
+
[7, 11, 13, 17]
|
170 |
+
|
171 |
+
All primes through the 10th prime
|
172 |
+
|
173 |
+
>>> list(sieve.primerange(prime(10) + 1))
|
174 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
175 |
+
|
176 |
+
"""
|
177 |
+
|
178 |
+
if b is None:
|
179 |
+
b = _as_int_ceiling(a)
|
180 |
+
a = 2
|
181 |
+
else:
|
182 |
+
a = max(2, _as_int_ceiling(a))
|
183 |
+
b = _as_int_ceiling(b)
|
184 |
+
if a >= b:
|
185 |
+
return
|
186 |
+
self.extend(b)
|
187 |
+
i = self.search(a)[1]
|
188 |
+
maxi = len(self._list) + 1
|
189 |
+
while i < maxi:
|
190 |
+
p = self._list[i - 1]
|
191 |
+
if p < b:
|
192 |
+
yield p
|
193 |
+
i += 1
|
194 |
+
else:
|
195 |
+
return
|
196 |
+
|
197 |
+
def totientrange(self, a, b):
|
198 |
+
"""Generate all totient numbers for the range [a, b).
|
199 |
+
|
200 |
+
Examples
|
201 |
+
========
|
202 |
+
|
203 |
+
>>> from sympy import sieve
|
204 |
+
>>> print([i for i in sieve.totientrange(7, 18)])
|
205 |
+
[6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
|
206 |
+
"""
|
207 |
+
a = max(1, _as_int_ceiling(a))
|
208 |
+
b = _as_int_ceiling(b)
|
209 |
+
n = len(self._tlist)
|
210 |
+
if a >= b:
|
211 |
+
return
|
212 |
+
elif b <= n:
|
213 |
+
for i in range(a, b):
|
214 |
+
yield self._tlist[i]
|
215 |
+
else:
|
216 |
+
self._tlist += _arange(n, b)
|
217 |
+
for i in range(1, n):
|
218 |
+
ti = self._tlist[i]
|
219 |
+
startindex = (n + i - 1) // i * i
|
220 |
+
for j in range(startindex, b, i):
|
221 |
+
self._tlist[j] -= ti
|
222 |
+
if i >= a:
|
223 |
+
yield ti
|
224 |
+
|
225 |
+
for i in range(n, b):
|
226 |
+
ti = self._tlist[i]
|
227 |
+
for j in range(2 * i, b, i):
|
228 |
+
self._tlist[j] -= ti
|
229 |
+
if i >= a:
|
230 |
+
yield ti
|
231 |
+
|
232 |
+
def mobiusrange(self, a, b):
|
233 |
+
"""Generate all mobius numbers for the range [a, b).
|
234 |
+
|
235 |
+
Parameters
|
236 |
+
==========
|
237 |
+
|
238 |
+
a : integer
|
239 |
+
First number in range
|
240 |
+
|
241 |
+
b : integer
|
242 |
+
First number outside of range
|
243 |
+
|
244 |
+
Examples
|
245 |
+
========
|
246 |
+
|
247 |
+
>>> from sympy import sieve
|
248 |
+
>>> print([i for i in sieve.mobiusrange(7, 18)])
|
249 |
+
[-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
|
250 |
+
"""
|
251 |
+
a = max(1, _as_int_ceiling(a))
|
252 |
+
b = _as_int_ceiling(b)
|
253 |
+
n = len(self._mlist)
|
254 |
+
if a >= b:
|
255 |
+
return
|
256 |
+
elif b <= n:
|
257 |
+
for i in range(a, b):
|
258 |
+
yield self._mlist[i]
|
259 |
+
else:
|
260 |
+
self._mlist += _azeros(b - n)
|
261 |
+
for i in range(1, n):
|
262 |
+
mi = self._mlist[i]
|
263 |
+
startindex = (n + i - 1) // i * i
|
264 |
+
for j in range(startindex, b, i):
|
265 |
+
self._mlist[j] -= mi
|
266 |
+
if i >= a:
|
267 |
+
yield mi
|
268 |
+
|
269 |
+
for i in range(n, b):
|
270 |
+
mi = self._mlist[i]
|
271 |
+
for j in range(2 * i, b, i):
|
272 |
+
self._mlist[j] -= mi
|
273 |
+
if i >= a:
|
274 |
+
yield mi
|
275 |
+
|
276 |
+
def search(self, n):
|
277 |
+
"""Return the indices i, j of the primes that bound n.
|
278 |
+
|
279 |
+
If n is prime then i == j.
|
280 |
+
|
281 |
+
Although n can be an expression, if ceiling cannot convert
|
282 |
+
it to an integer then an n error will be raised.
|
283 |
+
|
284 |
+
Examples
|
285 |
+
========
|
286 |
+
|
287 |
+
>>> from sympy import sieve
|
288 |
+
>>> sieve.search(25)
|
289 |
+
(9, 10)
|
290 |
+
>>> sieve.search(23)
|
291 |
+
(9, 9)
|
292 |
+
"""
|
293 |
+
test = _as_int_ceiling(n)
|
294 |
+
n = as_int(n)
|
295 |
+
if n < 2:
|
296 |
+
raise ValueError("n should be >= 2 but got: %s" % n)
|
297 |
+
if n > self._list[-1]:
|
298 |
+
self.extend(n)
|
299 |
+
b = bisect(self._list, n)
|
300 |
+
if self._list[b - 1] == test:
|
301 |
+
return b, b
|
302 |
+
else:
|
303 |
+
return b, b + 1
|
304 |
+
|
305 |
+
def __contains__(self, n):
|
306 |
+
try:
|
307 |
+
n = as_int(n)
|
308 |
+
assert n >= 2
|
309 |
+
except (ValueError, AssertionError):
|
310 |
+
return False
|
311 |
+
if n % 2 == 0:
|
312 |
+
return n == 2
|
313 |
+
a, b = self.search(n)
|
314 |
+
return a == b
|
315 |
+
|
316 |
+
def __iter__(self):
|
317 |
+
for n in count(1):
|
318 |
+
yield self[n]
|
319 |
+
|
320 |
+
def __getitem__(self, n):
|
321 |
+
"""Return the nth prime number"""
|
322 |
+
if isinstance(n, slice):
|
323 |
+
self.extend_to_no(n.stop)
|
324 |
+
# Python 2.7 slices have 0 instead of None for start, so
|
325 |
+
# we can't default to 1.
|
326 |
+
start = n.start if n.start is not None else 0
|
327 |
+
if start < 1:
|
328 |
+
# sieve[:5] would be empty (starting at -1), let's
|
329 |
+
# just be explicit and raise.
|
330 |
+
raise IndexError("Sieve indices start at 1.")
|
331 |
+
return self._list[start - 1:n.stop - 1:n.step]
|
332 |
+
else:
|
333 |
+
if n < 1:
|
334 |
+
# offset is one, so forbid explicit access to sieve[0]
|
335 |
+
# (would surprisingly return the last one).
|
336 |
+
raise IndexError("Sieve indices start at 1.")
|
337 |
+
n = as_int(n)
|
338 |
+
self.extend_to_no(n)
|
339 |
+
return self._list[n - 1]
|
340 |
+
|
341 |
+
# Generate a global object for repeated use in trial division etc
|
342 |
+
sieve = Sieve()
|
343 |
+
|
344 |
+
|
345 |
+
def prime(nth):
|
346 |
+
r""" Return the nth prime, with the primes indexed as prime(1) = 2,
|
347 |
+
prime(2) = 3, etc.... The nth prime is approximately $n\log(n)$.
|
348 |
+
|
349 |
+
Logarithmic integral of $x$ is a pretty nice approximation for number of
|
350 |
+
primes $\le x$, i.e.
|
351 |
+
li(x) ~ pi(x)
|
352 |
+
In fact, for the numbers we are concerned about( x<1e11 ),
|
353 |
+
li(x) - pi(x) < 50000
|
354 |
+
|
355 |
+
Also,
|
356 |
+
li(x) > pi(x) can be safely assumed for the numbers which
|
357 |
+
can be evaluated by this function.
|
358 |
+
|
359 |
+
Here, we find the least integer m such that li(m) > n using binary search.
|
360 |
+
Now pi(m-1) < li(m-1) <= n,
|
361 |
+
|
362 |
+
We find pi(m - 1) using primepi function.
|
363 |
+
|
364 |
+
Starting from m, we have to find n - pi(m-1) more primes.
|
365 |
+
|
366 |
+
For the inputs this implementation can handle, we will have to test
|
367 |
+
primality for at max about 10**5 numbers, to get our answer.
|
368 |
+
|
369 |
+
Examples
|
370 |
+
========
|
371 |
+
|
372 |
+
>>> from sympy import prime
|
373 |
+
>>> prime(10)
|
374 |
+
29
|
375 |
+
>>> prime(1)
|
376 |
+
2
|
377 |
+
>>> prime(100000)
|
378 |
+
1299709
|
379 |
+
|
380 |
+
See Also
|
381 |
+
========
|
382 |
+
|
383 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
384 |
+
primerange : Generate all primes in a given range
|
385 |
+
primepi : Return the number of primes less than or equal to n
|
386 |
+
|
387 |
+
References
|
388 |
+
==========
|
389 |
+
|
390 |
+
.. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29
|
391 |
+
.. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
|
392 |
+
.. [3] https://en.wikipedia.org/wiki/Skewes%27_number
|
393 |
+
"""
|
394 |
+
n = as_int(nth)
|
395 |
+
if n < 1:
|
396 |
+
raise ValueError("nth must be a positive integer; prime(1) == 2")
|
397 |
+
if n <= len(sieve._list):
|
398 |
+
return sieve[n]
|
399 |
+
|
400 |
+
from sympy.functions.elementary.exponential import log
|
401 |
+
from sympy.functions.special.error_functions import li
|
402 |
+
a = 2 # Lower bound for binary search
|
403 |
+
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
|
404 |
+
|
405 |
+
while a < b:
|
406 |
+
mid = (a + b) >> 1
|
407 |
+
if li(mid) > n:
|
408 |
+
b = mid
|
409 |
+
else:
|
410 |
+
a = mid + 1
|
411 |
+
n_primes = primepi(a - 1)
|
412 |
+
while n_primes < n:
|
413 |
+
if isprime(a):
|
414 |
+
n_primes += 1
|
415 |
+
a += 1
|
416 |
+
return a - 1
|
417 |
+
|
418 |
+
|
419 |
+
class primepi(Function):
|
420 |
+
r""" Represents the prime counting function pi(n) = the number
|
421 |
+
of prime numbers less than or equal to n.
|
422 |
+
|
423 |
+
Algorithm Description:
|
424 |
+
|
425 |
+
In sieve method, we remove all multiples of prime p
|
426 |
+
except p itself.
|
427 |
+
|
428 |
+
Let phi(i,j) be the number of integers 2 <= k <= i
|
429 |
+
which remain after sieving from primes less than
|
430 |
+
or equal to j.
|
431 |
+
Clearly, pi(n) = phi(n, sqrt(n))
|
432 |
+
|
433 |
+
If j is not a prime,
|
434 |
+
phi(i,j) = phi(i, j - 1)
|
435 |
+
|
436 |
+
if j is a prime,
|
437 |
+
We remove all numbers(except j) whose
|
438 |
+
smallest prime factor is j.
|
439 |
+
|
440 |
+
Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
|
441 |
+
Now, after sieving from primes $\le j - 1$,
|
442 |
+
a must remain
|
443 |
+
(because x, and hence a has no prime factor $\le j - 1$)
|
444 |
+
Clearly, there are phi(i / j, j - 1) such a
|
445 |
+
which remain on sieving from primes $\le j - 1$
|
446 |
+
|
447 |
+
Now, if a is a prime less than equal to j - 1,
|
448 |
+
$x= j \times a$ has smallest prime factor = a, and
|
449 |
+
has already been removed(by sieving from a).
|
450 |
+
So, we do not need to remove it again.
|
451 |
+
(Note: there will be pi(j - 1) such x)
|
452 |
+
|
453 |
+
Thus, number of x, that will be removed are:
|
454 |
+
phi(i / j, j - 1) - phi(j - 1, j - 1)
|
455 |
+
(Note that pi(j - 1) = phi(j - 1, j - 1))
|
456 |
+
|
457 |
+
$\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
|
458 |
+
|
459 |
+
So,following recursion is used and implemented as dp:
|
460 |
+
|
461 |
+
phi(a, b) = phi(a, b - 1), if b is not a prime
|
462 |
+
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
|
463 |
+
|
464 |
+
Clearly a is always of the form floor(n / k),
|
465 |
+
which can take at most $2\sqrt{n}$ values.
|
466 |
+
Two arrays arr1,arr2 are maintained
|
467 |
+
arr1[i] = phi(i, j),
|
468 |
+
arr2[i] = phi(n // i, j)
|
469 |
+
|
470 |
+
Finally the answer is arr2[1]
|
471 |
+
|
472 |
+
Examples
|
473 |
+
========
|
474 |
+
|
475 |
+
>>> from sympy import primepi, prime, prevprime, isprime
|
476 |
+
>>> primepi(25)
|
477 |
+
9
|
478 |
+
|
479 |
+
So there are 9 primes less than or equal to 25. Is 25 prime?
|
480 |
+
|
481 |
+
>>> isprime(25)
|
482 |
+
False
|
483 |
+
|
484 |
+
It is not. So the first prime less than 25 must be the
|
485 |
+
9th prime:
|
486 |
+
|
487 |
+
>>> prevprime(25) == prime(9)
|
488 |
+
True
|
489 |
+
|
490 |
+
See Also
|
491 |
+
========
|
492 |
+
|
493 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
494 |
+
primerange : Generate all primes in a given range
|
495 |
+
prime : Return the nth prime
|
496 |
+
"""
|
497 |
+
@classmethod
|
498 |
+
def eval(cls, n):
|
499 |
+
if n is S.Infinity:
|
500 |
+
return S.Infinity
|
501 |
+
if n is S.NegativeInfinity:
|
502 |
+
return S.Zero
|
503 |
+
|
504 |
+
try:
|
505 |
+
n = int(n)
|
506 |
+
except TypeError:
|
507 |
+
if n.is_real == False or n is S.NaN:
|
508 |
+
raise ValueError("n must be real")
|
509 |
+
return
|
510 |
+
|
511 |
+
if n < 2:
|
512 |
+
return S.Zero
|
513 |
+
if n <= sieve._list[-1]:
|
514 |
+
return S(sieve.search(n)[0])
|
515 |
+
lim = int(n ** 0.5)
|
516 |
+
lim -= 1
|
517 |
+
lim = max(lim, 0)
|
518 |
+
while lim * lim <= n:
|
519 |
+
lim += 1
|
520 |
+
lim -= 1
|
521 |
+
arr1 = [0] * (lim + 1)
|
522 |
+
arr2 = [0] * (lim + 1)
|
523 |
+
for i in range(1, lim + 1):
|
524 |
+
arr1[i] = i - 1
|
525 |
+
arr2[i] = n // i - 1
|
526 |
+
for i in range(2, lim + 1):
|
527 |
+
# Presently, arr1[k]=phi(k,i - 1),
|
528 |
+
# arr2[k] = phi(n // k,i - 1)
|
529 |
+
if arr1[i] == arr1[i - 1]:
|
530 |
+
continue
|
531 |
+
p = arr1[i - 1]
|
532 |
+
for j in range(1, min(n // (i * i), lim) + 1):
|
533 |
+
st = i * j
|
534 |
+
if st <= lim:
|
535 |
+
arr2[j] -= arr2[st] - p
|
536 |
+
else:
|
537 |
+
arr2[j] -= arr1[n // st] - p
|
538 |
+
lim2 = min(lim, i * i - 1)
|
539 |
+
for j in range(lim, lim2, -1):
|
540 |
+
arr1[j] -= arr1[j // i] - p
|
541 |
+
return S(arr2[1])
|
542 |
+
|
543 |
+
|
544 |
+
def nextprime(n, ith=1):
|
545 |
+
""" Return the ith prime greater than n.
|
546 |
+
|
547 |
+
i must be an integer.
|
548 |
+
|
549 |
+
Notes
|
550 |
+
=====
|
551 |
+
|
552 |
+
Potential primes are located at 6*j +/- 1. This
|
553 |
+
property is used during searching.
|
554 |
+
|
555 |
+
>>> from sympy import nextprime
|
556 |
+
>>> [(i, nextprime(i)) for i in range(10, 15)]
|
557 |
+
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
|
558 |
+
>>> nextprime(2, ith=2) # the 2nd prime after 2
|
559 |
+
5
|
560 |
+
|
561 |
+
See Also
|
562 |
+
========
|
563 |
+
|
564 |
+
prevprime : Return the largest prime smaller than n
|
565 |
+
primerange : Generate all primes in a given range
|
566 |
+
|
567 |
+
"""
|
568 |
+
n = int(n)
|
569 |
+
i = as_int(ith)
|
570 |
+
if i > 1:
|
571 |
+
pr = n
|
572 |
+
j = 1
|
573 |
+
while 1:
|
574 |
+
pr = nextprime(pr)
|
575 |
+
j += 1
|
576 |
+
if j > i:
|
577 |
+
break
|
578 |
+
return pr
|
579 |
+
|
580 |
+
if n < 2:
|
581 |
+
return 2
|
582 |
+
if n < 7:
|
583 |
+
return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n]
|
584 |
+
if n <= sieve._list[-2]:
|
585 |
+
l, u = sieve.search(n)
|
586 |
+
if l == u:
|
587 |
+
return sieve[u + 1]
|
588 |
+
else:
|
589 |
+
return sieve[u]
|
590 |
+
nn = 6*(n//6)
|
591 |
+
if nn == n:
|
592 |
+
n += 1
|
593 |
+
if isprime(n):
|
594 |
+
return n
|
595 |
+
n += 4
|
596 |
+
elif n - nn == 5:
|
597 |
+
n += 2
|
598 |
+
if isprime(n):
|
599 |
+
return n
|
600 |
+
n += 4
|
601 |
+
else:
|
602 |
+
n = nn + 5
|
603 |
+
while 1:
|
604 |
+
if isprime(n):
|
605 |
+
return n
|
606 |
+
n += 2
|
607 |
+
if isprime(n):
|
608 |
+
return n
|
609 |
+
n += 4
|
610 |
+
|
611 |
+
|
612 |
+
def prevprime(n):
|
613 |
+
""" Return the largest prime smaller than n.
|
614 |
+
|
615 |
+
Notes
|
616 |
+
=====
|
617 |
+
|
618 |
+
Potential primes are located at 6*j +/- 1. This
|
619 |
+
property is used during searching.
|
620 |
+
|
621 |
+
>>> from sympy import prevprime
|
622 |
+
>>> [(i, prevprime(i)) for i in range(10, 15)]
|
623 |
+
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
|
624 |
+
|
625 |
+
See Also
|
626 |
+
========
|
627 |
+
|
628 |
+
nextprime : Return the ith prime greater than n
|
629 |
+
primerange : Generates all primes in a given range
|
630 |
+
"""
|
631 |
+
n = _as_int_ceiling(n)
|
632 |
+
if n < 3:
|
633 |
+
raise ValueError("no preceding primes")
|
634 |
+
if n < 8:
|
635 |
+
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
|
636 |
+
if n <= sieve._list[-1]:
|
637 |
+
l, u = sieve.search(n)
|
638 |
+
if l == u:
|
639 |
+
return sieve[l-1]
|
640 |
+
else:
|
641 |
+
return sieve[l]
|
642 |
+
nn = 6*(n//6)
|
643 |
+
if n - nn <= 1:
|
644 |
+
n = nn - 1
|
645 |
+
if isprime(n):
|
646 |
+
return n
|
647 |
+
n -= 4
|
648 |
+
else:
|
649 |
+
n = nn + 1
|
650 |
+
while 1:
|
651 |
+
if isprime(n):
|
652 |
+
return n
|
653 |
+
n -= 2
|
654 |
+
if isprime(n):
|
655 |
+
return n
|
656 |
+
n -= 4
|
657 |
+
|
658 |
+
|
659 |
+
def primerange(a, b=None):
|
660 |
+
""" Generate a list of all prime numbers in the range [2, a),
|
661 |
+
or [a, b).
|
662 |
+
|
663 |
+
If the range exists in the default sieve, the values will
|
664 |
+
be returned from there; otherwise values will be returned
|
665 |
+
but will not modify the sieve.
|
666 |
+
|
667 |
+
Examples
|
668 |
+
========
|
669 |
+
|
670 |
+
>>> from sympy import primerange, prime
|
671 |
+
|
672 |
+
All primes less than 19:
|
673 |
+
|
674 |
+
>>> list(primerange(19))
|
675 |
+
[2, 3, 5, 7, 11, 13, 17]
|
676 |
+
|
677 |
+
All primes greater than or equal to 7 and less than 19:
|
678 |
+
|
679 |
+
>>> list(primerange(7, 19))
|
680 |
+
[7, 11, 13, 17]
|
681 |
+
|
682 |
+
All primes through the 10th prime
|
683 |
+
|
684 |
+
>>> list(primerange(prime(10) + 1))
|
685 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
686 |
+
|
687 |
+
The Sieve method, primerange, is generally faster but it will
|
688 |
+
occupy more memory as the sieve stores values. The default
|
689 |
+
instance of Sieve, named sieve, can be used:
|
690 |
+
|
691 |
+
>>> from sympy import sieve
|
692 |
+
>>> list(sieve.primerange(1, 30))
|
693 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
694 |
+
|
695 |
+
Notes
|
696 |
+
=====
|
697 |
+
|
698 |
+
Some famous conjectures about the occurrence of primes in a given
|
699 |
+
range are [1]:
|
700 |
+
|
701 |
+
- Twin primes: though often not, the following will give 2 primes
|
702 |
+
an infinite number of times:
|
703 |
+
primerange(6*n - 1, 6*n + 2)
|
704 |
+
- Legendre's: the following always yields at least one prime
|
705 |
+
primerange(n**2, (n+1)**2+1)
|
706 |
+
- Bertrand's (proven): there is always a prime in the range
|
707 |
+
primerange(n, 2*n)
|
708 |
+
- Brocard's: there are at least four primes in the range
|
709 |
+
primerange(prime(n)**2, prime(n+1)**2)
|
710 |
+
|
711 |
+
The average gap between primes is log(n) [2]; the gap between
|
712 |
+
primes can be arbitrarily large since sequences of composite
|
713 |
+
numbers are arbitrarily large, e.g. the numbers in the sequence
|
714 |
+
n! + 2, n! + 3 ... n! + n are all composite.
|
715 |
+
|
716 |
+
See Also
|
717 |
+
========
|
718 |
+
|
719 |
+
prime : Return the nth prime
|
720 |
+
nextprime : Return the ith prime greater than n
|
721 |
+
prevprime : Return the largest prime smaller than n
|
722 |
+
randprime : Returns a random prime in a given range
|
723 |
+
primorial : Returns the product of primes based on condition
|
724 |
+
Sieve.primerange : return range from already computed primes
|
725 |
+
or extend the sieve to contain the requested
|
726 |
+
range.
|
727 |
+
|
728 |
+
References
|
729 |
+
==========
|
730 |
+
|
731 |
+
.. [1] https://en.wikipedia.org/wiki/Prime_number
|
732 |
+
.. [2] https://primes.utm.edu/notes/gaps.html
|
733 |
+
"""
|
734 |
+
if b is None:
|
735 |
+
a, b = 2, a
|
736 |
+
if a >= b:
|
737 |
+
return
|
738 |
+
# if we already have the range, return it
|
739 |
+
if b <= sieve._list[-1]:
|
740 |
+
yield from sieve.primerange(a, b)
|
741 |
+
return
|
742 |
+
# otherwise compute, without storing, the desired range.
|
743 |
+
|
744 |
+
a = _as_int_ceiling(a) - 1
|
745 |
+
b = _as_int_ceiling(b)
|
746 |
+
while 1:
|
747 |
+
a = nextprime(a)
|
748 |
+
if a < b:
|
749 |
+
yield a
|
750 |
+
else:
|
751 |
+
return
|
752 |
+
|
753 |
+
|
754 |
+
def randprime(a, b):
|
755 |
+
""" Return a random prime number in the range [a, b).
|
756 |
+
|
757 |
+
Bertrand's postulate assures that
|
758 |
+
randprime(a, 2*a) will always succeed for a > 1.
|
759 |
+
|
760 |
+
Examples
|
761 |
+
========
|
762 |
+
|
763 |
+
>>> from sympy import randprime, isprime
|
764 |
+
>>> randprime(1, 30) #doctest: +SKIP
|
765 |
+
13
|
766 |
+
>>> isprime(randprime(1, 30))
|
767 |
+
True
|
768 |
+
|
769 |
+
See Also
|
770 |
+
========
|
771 |
+
|
772 |
+
primerange : Generate all primes in a given range
|
773 |
+
|
774 |
+
References
|
775 |
+
==========
|
776 |
+
|
777 |
+
.. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
|
778 |
+
|
779 |
+
"""
|
780 |
+
if a >= b:
|
781 |
+
return
|
782 |
+
a, b = map(int, (a, b))
|
783 |
+
n = random.randint(a - 1, b)
|
784 |
+
p = nextprime(n)
|
785 |
+
if p >= b:
|
786 |
+
p = prevprime(b)
|
787 |
+
if p < a:
|
788 |
+
raise ValueError("no primes exist in the specified range")
|
789 |
+
return p
|
790 |
+
|
791 |
+
|
792 |
+
def primorial(n, nth=True):
|
793 |
+
"""
|
794 |
+
Returns the product of the first n primes (default) or
|
795 |
+
the primes less than or equal to n (when ``nth=False``).
|
796 |
+
|
797 |
+
Examples
|
798 |
+
========
|
799 |
+
|
800 |
+
>>> from sympy.ntheory.generate import primorial, primerange
|
801 |
+
>>> from sympy import factorint, Mul, primefactors, sqrt
|
802 |
+
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
|
803 |
+
210
|
804 |
+
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
|
805 |
+
6
|
806 |
+
>>> primorial(1)
|
807 |
+
2
|
808 |
+
>>> primorial(1, nth=False)
|
809 |
+
1
|
810 |
+
>>> primorial(sqrt(101), nth=False)
|
811 |
+
210
|
812 |
+
|
813 |
+
One can argue that the primes are infinite since if you take
|
814 |
+
a set of primes and multiply them together (e.g. the primorial) and
|
815 |
+
then add or subtract 1, the result cannot be divided by any of the
|
816 |
+
original factors, hence either 1 or more new primes must divide this
|
817 |
+
product of primes.
|
818 |
+
|
819 |
+
In this case, the number itself is a new prime:
|
820 |
+
|
821 |
+
>>> factorint(primorial(4) + 1)
|
822 |
+
{211: 1}
|
823 |
+
|
824 |
+
In this case two new primes are the factors:
|
825 |
+
|
826 |
+
>>> factorint(primorial(4) - 1)
|
827 |
+
{11: 1, 19: 1}
|
828 |
+
|
829 |
+
Here, some primes smaller and larger than the primes multiplied together
|
830 |
+
are obtained:
|
831 |
+
|
832 |
+
>>> p = list(primerange(10, 20))
|
833 |
+
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
|
834 |
+
[2, 5, 31, 149]
|
835 |
+
|
836 |
+
See Also
|
837 |
+
========
|
838 |
+
|
839 |
+
primerange : Generate all primes in a given range
|
840 |
+
|
841 |
+
"""
|
842 |
+
if nth:
|
843 |
+
n = as_int(n)
|
844 |
+
else:
|
845 |
+
n = int(n)
|
846 |
+
if n < 1:
|
847 |
+
raise ValueError("primorial argument must be >= 1")
|
848 |
+
p = 1
|
849 |
+
if nth:
|
850 |
+
for i in range(1, n + 1):
|
851 |
+
p *= prime(i)
|
852 |
+
else:
|
853 |
+
for i in primerange(2, n + 1):
|
854 |
+
p *= i
|
855 |
+
return p
|
856 |
+
|
857 |
+
|
858 |
+
def cycle_length(f, x0, nmax=None, values=False):
|
859 |
+
"""For a given iterated sequence, return a generator that gives
|
860 |
+
the length of the iterated cycle (lambda) and the length of terms
|
861 |
+
before the cycle begins (mu); if ``values`` is True then the
|
862 |
+
terms of the sequence will be returned instead. The sequence is
|
863 |
+
started with value ``x0``.
|
864 |
+
|
865 |
+
Note: more than the first lambda + mu terms may be returned and this
|
866 |
+
is the cost of cycle detection with Brent's method; there are, however,
|
867 |
+
generally less terms calculated than would have been calculated if the
|
868 |
+
proper ending point were determined, e.g. by using Floyd's method.
|
869 |
+
|
870 |
+
>>> from sympy.ntheory.generate import cycle_length
|
871 |
+
|
872 |
+
This will yield successive values of i <-- func(i):
|
873 |
+
|
874 |
+
>>> def iter(func, i):
|
875 |
+
... while 1:
|
876 |
+
... ii = func(i)
|
877 |
+
... yield ii
|
878 |
+
... i = ii
|
879 |
+
...
|
880 |
+
|
881 |
+
A function is defined:
|
882 |
+
|
883 |
+
>>> func = lambda i: (i**2 + 1) % 51
|
884 |
+
|
885 |
+
and given a seed of 4 and the mu and lambda terms calculated:
|
886 |
+
|
887 |
+
>>> next(cycle_length(func, 4))
|
888 |
+
(6, 2)
|
889 |
+
|
890 |
+
We can see what is meant by looking at the output:
|
891 |
+
|
892 |
+
>>> n = cycle_length(func, 4, values=True)
|
893 |
+
>>> list(ni for ni in n)
|
894 |
+
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
|
895 |
+
|
896 |
+
There are 6 repeating values after the first 2.
|
897 |
+
|
898 |
+
If a sequence is suspected of being longer than you might wish, ``nmax``
|
899 |
+
can be used to exit early (and mu will be returned as None):
|
900 |
+
|
901 |
+
>>> next(cycle_length(func, 4, nmax = 4))
|
902 |
+
(4, None)
|
903 |
+
>>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]
|
904 |
+
[17, 35, 2, 5]
|
905 |
+
|
906 |
+
Code modified from:
|
907 |
+
https://en.wikipedia.org/wiki/Cycle_detection.
|
908 |
+
"""
|
909 |
+
|
910 |
+
nmax = int(nmax or 0)
|
911 |
+
|
912 |
+
# main phase: search successive powers of two
|
913 |
+
power = lam = 1
|
914 |
+
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
|
915 |
+
i = 0
|
916 |
+
while tortoise != hare and (not nmax or i < nmax):
|
917 |
+
i += 1
|
918 |
+
if power == lam: # time to start a new power of two?
|
919 |
+
tortoise = hare
|
920 |
+
power *= 2
|
921 |
+
lam = 0
|
922 |
+
if values:
|
923 |
+
yield hare
|
924 |
+
hare = f(hare)
|
925 |
+
lam += 1
|
926 |
+
if nmax and i == nmax:
|
927 |
+
if values:
|
928 |
+
return
|
929 |
+
else:
|
930 |
+
yield nmax, None
|
931 |
+
return
|
932 |
+
if not values:
|
933 |
+
# Find the position of the first repetition of length lambda
|
934 |
+
mu = 0
|
935 |
+
tortoise = hare = x0
|
936 |
+
for i in range(lam):
|
937 |
+
hare = f(hare)
|
938 |
+
while tortoise != hare:
|
939 |
+
tortoise = f(tortoise)
|
940 |
+
hare = f(hare)
|
941 |
+
mu += 1
|
942 |
+
if mu:
|
943 |
+
mu -= 1
|
944 |
+
yield lam, mu
|
945 |
+
|
946 |
+
|
947 |
+
def composite(nth):
|
948 |
+
""" Return the nth composite number, with the composite numbers indexed as
|
949 |
+
composite(1) = 4, composite(2) = 6, etc....
|
950 |
+
|
951 |
+
Examples
|
952 |
+
========
|
953 |
+
|
954 |
+
>>> from sympy import composite
|
955 |
+
>>> composite(36)
|
956 |
+
52
|
957 |
+
>>> composite(1)
|
958 |
+
4
|
959 |
+
>>> composite(17737)
|
960 |
+
20000
|
961 |
+
|
962 |
+
See Also
|
963 |
+
========
|
964 |
+
|
965 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
966 |
+
primerange : Generate all primes in a given range
|
967 |
+
primepi : Return the number of primes less than or equal to n
|
968 |
+
prime : Return the nth prime
|
969 |
+
compositepi : Return the number of positive composite numbers less than or equal to n
|
970 |
+
"""
|
971 |
+
n = as_int(nth)
|
972 |
+
if n < 1:
|
973 |
+
raise ValueError("nth must be a positive integer; composite(1) == 4")
|
974 |
+
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
|
975 |
+
if n <= 10:
|
976 |
+
return composite_arr[n - 1]
|
977 |
+
|
978 |
+
a, b = 4, sieve._list[-1]
|
979 |
+
if n <= b - primepi(b) - 1:
|
980 |
+
while a < b - 1:
|
981 |
+
mid = (a + b) >> 1
|
982 |
+
if mid - primepi(mid) - 1 > n:
|
983 |
+
b = mid
|
984 |
+
else:
|
985 |
+
a = mid
|
986 |
+
if isprime(a):
|
987 |
+
a -= 1
|
988 |
+
return a
|
989 |
+
|
990 |
+
from sympy.functions.elementary.exponential import log
|
991 |
+
from sympy.functions.special.error_functions import li
|
992 |
+
a = 4 # Lower bound for binary search
|
993 |
+
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
|
994 |
+
|
995 |
+
while a < b:
|
996 |
+
mid = (a + b) >> 1
|
997 |
+
if mid - li(mid) - 1 > n:
|
998 |
+
b = mid
|
999 |
+
else:
|
1000 |
+
a = mid + 1
|
1001 |
+
|
1002 |
+
n_composites = a - primepi(a) - 1
|
1003 |
+
while n_composites > n:
|
1004 |
+
if not isprime(a):
|
1005 |
+
n_composites -= 1
|
1006 |
+
a -= 1
|
1007 |
+
if isprime(a):
|
1008 |
+
a -= 1
|
1009 |
+
return a
|
1010 |
+
|
1011 |
+
|
1012 |
+
def compositepi(n):
|
1013 |
+
""" Return the number of positive composite numbers less than or equal to n.
|
1014 |
+
The first positive composite is 4, i.e. compositepi(4) = 1.
|
1015 |
+
|
1016 |
+
Examples
|
1017 |
+
========
|
1018 |
+
|
1019 |
+
>>> from sympy import compositepi
|
1020 |
+
>>> compositepi(25)
|
1021 |
+
15
|
1022 |
+
>>> compositepi(1000)
|
1023 |
+
831
|
1024 |
+
|
1025 |
+
See Also
|
1026 |
+
========
|
1027 |
+
|
1028 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
1029 |
+
primerange : Generate all primes in a given range
|
1030 |
+
prime : Return the nth prime
|
1031 |
+
primepi : Return the number of primes less than or equal to n
|
1032 |
+
composite : Return the nth composite number
|
1033 |
+
"""
|
1034 |
+
n = int(n)
|
1035 |
+
if n < 4:
|
1036 |
+
return 0
|
1037 |
+
return n - primepi(n) - 1
|
venv/lib/python3.10/site-packages/sympy/ntheory/modular.py
ADDED
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import reduce
|
2 |
+
from math import prod
|
3 |
+
|
4 |
+
from sympy.core.numbers import igcdex, igcd
|
5 |
+
from sympy.ntheory.primetest import isprime
|
6 |
+
from sympy.polys.domains import ZZ
|
7 |
+
from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
|
8 |
+
from sympy.utilities.misc import as_int
|
9 |
+
|
10 |
+
|
11 |
+
def symmetric_residue(a, m):
|
12 |
+
"""Return the residual mod m such that it is within half of the modulus.
|
13 |
+
|
14 |
+
>>> from sympy.ntheory.modular import symmetric_residue
|
15 |
+
>>> symmetric_residue(1, 6)
|
16 |
+
1
|
17 |
+
>>> symmetric_residue(4, 6)
|
18 |
+
-2
|
19 |
+
"""
|
20 |
+
if a <= m // 2:
|
21 |
+
return a
|
22 |
+
return a - m
|
23 |
+
|
24 |
+
|
25 |
+
def crt(m, v, symmetric=False, check=True):
|
26 |
+
r"""Chinese Remainder Theorem.
|
27 |
+
|
28 |
+
The moduli in m are assumed to be pairwise coprime. The output
|
29 |
+
is then an integer f, such that f = v_i mod m_i for each pair out
|
30 |
+
of v and m. If ``symmetric`` is False a positive integer will be
|
31 |
+
returned, else \|f\| will be less than or equal to the LCM of the
|
32 |
+
moduli, and thus f may be negative.
|
33 |
+
|
34 |
+
If the moduli are not co-prime the correct result will be returned
|
35 |
+
if/when the test of the result is found to be incorrect. This result
|
36 |
+
will be None if there is no solution.
|
37 |
+
|
38 |
+
The keyword ``check`` can be set to False if it is known that the moduli
|
39 |
+
are coprime.
|
40 |
+
|
41 |
+
Examples
|
42 |
+
========
|
43 |
+
|
44 |
+
As an example consider a set of residues ``U = [49, 76, 65]``
|
45 |
+
and a set of moduli ``M = [99, 97, 95]``. Then we have::
|
46 |
+
|
47 |
+
>>> from sympy.ntheory.modular import crt
|
48 |
+
|
49 |
+
>>> crt([99, 97, 95], [49, 76, 65])
|
50 |
+
(639985, 912285)
|
51 |
+
|
52 |
+
This is the correct result because::
|
53 |
+
|
54 |
+
>>> [639985 % m for m in [99, 97, 95]]
|
55 |
+
[49, 76, 65]
|
56 |
+
|
57 |
+
If the moduli are not co-prime, you may receive an incorrect result
|
58 |
+
if you use ``check=False``:
|
59 |
+
|
60 |
+
>>> crt([12, 6, 17], [3, 4, 2], check=False)
|
61 |
+
(954, 1224)
|
62 |
+
>>> [954 % m for m in [12, 6, 17]]
|
63 |
+
[6, 0, 2]
|
64 |
+
>>> crt([12, 6, 17], [3, 4, 2]) is None
|
65 |
+
True
|
66 |
+
>>> crt([3, 6], [2, 5])
|
67 |
+
(5, 6)
|
68 |
+
|
69 |
+
Note: the order of gf_crt's arguments is reversed relative to crt,
|
70 |
+
and that solve_congruence takes residue, modulus pairs.
|
71 |
+
|
72 |
+
Programmer's note: rather than checking that all pairs of moduli share
|
73 |
+
no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
|
74 |
+
that there is no factor in common, a check that the result gives the
|
75 |
+
indicated residuals is performed -- an O(n) operation.
|
76 |
+
|
77 |
+
See Also
|
78 |
+
========
|
79 |
+
|
80 |
+
solve_congruence
|
81 |
+
sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
|
82 |
+
"""
|
83 |
+
if check:
|
84 |
+
m = list(map(as_int, m))
|
85 |
+
v = list(map(as_int, v))
|
86 |
+
|
87 |
+
result = gf_crt(v, m, ZZ)
|
88 |
+
mm = prod(m)
|
89 |
+
|
90 |
+
if check:
|
91 |
+
if not all(v % m == result % m for v, m in zip(v, m)):
|
92 |
+
result = solve_congruence(*list(zip(v, m)),
|
93 |
+
check=False, symmetric=symmetric)
|
94 |
+
if result is None:
|
95 |
+
return result
|
96 |
+
result, mm = result
|
97 |
+
|
98 |
+
if symmetric:
|
99 |
+
return symmetric_residue(result, mm), mm
|
100 |
+
return result, mm
|
101 |
+
|
102 |
+
|
103 |
+
def crt1(m):
|
104 |
+
"""First part of Chinese Remainder Theorem, for multiple application.
|
105 |
+
|
106 |
+
Examples
|
107 |
+
========
|
108 |
+
|
109 |
+
>>> from sympy.ntheory.modular import crt1
|
110 |
+
>>> crt1([18, 42, 6])
|
111 |
+
(4536, [252, 108, 756], [0, 2, 0])
|
112 |
+
"""
|
113 |
+
|
114 |
+
return gf_crt1(m, ZZ)
|
115 |
+
|
116 |
+
|
117 |
+
def crt2(m, v, mm, e, s, symmetric=False):
|
118 |
+
"""Second part of Chinese Remainder Theorem, for multiple application.
|
119 |
+
|
120 |
+
Examples
|
121 |
+
========
|
122 |
+
|
123 |
+
>>> from sympy.ntheory.modular import crt1, crt2
|
124 |
+
>>> mm, e, s = crt1([18, 42, 6])
|
125 |
+
>>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
|
126 |
+
(0, 4536)
|
127 |
+
"""
|
128 |
+
|
129 |
+
result = gf_crt2(v, m, mm, e, s, ZZ)
|
130 |
+
|
131 |
+
if symmetric:
|
132 |
+
return symmetric_residue(result, mm), mm
|
133 |
+
return result, mm
|
134 |
+
|
135 |
+
|
136 |
+
def solve_congruence(*remainder_modulus_pairs, **hint):
|
137 |
+
"""Compute the integer ``n`` that has the residual ``ai`` when it is
|
138 |
+
divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
|
139 |
+
this function: ((a1, m1), (a2, m2), ...). If there is no solution,
|
140 |
+
return None. Otherwise return ``n`` and its modulus.
|
141 |
+
|
142 |
+
The ``mi`` values need not be co-prime. If it is known that the moduli are
|
143 |
+
not co-prime then the hint ``check`` can be set to False (default=True) and
|
144 |
+
the check for a quicker solution via crt() (valid when the moduli are
|
145 |
+
co-prime) will be skipped.
|
146 |
+
|
147 |
+
If the hint ``symmetric`` is True (default is False), the value of ``n``
|
148 |
+
will be within 1/2 of the modulus, possibly negative.
|
149 |
+
|
150 |
+
Examples
|
151 |
+
========
|
152 |
+
|
153 |
+
>>> from sympy.ntheory.modular import solve_congruence
|
154 |
+
|
155 |
+
What number is 2 mod 3, 3 mod 5 and 2 mod 7?
|
156 |
+
|
157 |
+
>>> solve_congruence((2, 3), (3, 5), (2, 7))
|
158 |
+
(23, 105)
|
159 |
+
>>> [23 % m for m in [3, 5, 7]]
|
160 |
+
[2, 3, 2]
|
161 |
+
|
162 |
+
If you prefer to work with all remainder in one list and
|
163 |
+
all moduli in another, send the arguments like this:
|
164 |
+
|
165 |
+
>>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
|
166 |
+
(23, 105)
|
167 |
+
|
168 |
+
The moduli need not be co-prime; in this case there may or
|
169 |
+
may not be a solution:
|
170 |
+
|
171 |
+
>>> solve_congruence((2, 3), (4, 6)) is None
|
172 |
+
True
|
173 |
+
|
174 |
+
>>> solve_congruence((2, 3), (5, 6))
|
175 |
+
(5, 6)
|
176 |
+
|
177 |
+
The symmetric flag will make the result be within 1/2 of the modulus:
|
178 |
+
|
179 |
+
>>> solve_congruence((2, 3), (5, 6), symmetric=True)
|
180 |
+
(-1, 6)
|
181 |
+
|
182 |
+
See Also
|
183 |
+
========
|
184 |
+
|
185 |
+
crt : high level routine implementing the Chinese Remainder Theorem
|
186 |
+
|
187 |
+
"""
|
188 |
+
def combine(c1, c2):
|
189 |
+
"""Return the tuple (a, m) which satisfies the requirement
|
190 |
+
that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
|
191 |
+
|
192 |
+
References
|
193 |
+
==========
|
194 |
+
|
195 |
+
.. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution
|
196 |
+
"""
|
197 |
+
a1, m1 = c1
|
198 |
+
a2, m2 = c2
|
199 |
+
a, b, c = m1, a2 - a1, m2
|
200 |
+
g = reduce(igcd, [a, b, c])
|
201 |
+
a, b, c = [i//g for i in [a, b, c]]
|
202 |
+
if a != 1:
|
203 |
+
inv_a, _, g = igcdex(a, c)
|
204 |
+
if g != 1:
|
205 |
+
return None
|
206 |
+
b *= inv_a
|
207 |
+
a, m = a1 + m1*b, m1*c
|
208 |
+
return a, m
|
209 |
+
|
210 |
+
rm = remainder_modulus_pairs
|
211 |
+
symmetric = hint.get('symmetric', False)
|
212 |
+
|
213 |
+
if hint.get('check', True):
|
214 |
+
rm = [(as_int(r), as_int(m)) for r, m in rm]
|
215 |
+
|
216 |
+
# ignore redundant pairs but raise an error otherwise; also
|
217 |
+
# make sure that a unique set of bases is sent to gf_crt if
|
218 |
+
# they are all prime.
|
219 |
+
#
|
220 |
+
# The routine will work out less-trivial violations and
|
221 |
+
# return None, e.g. for the pairs (1,3) and (14,42) there
|
222 |
+
# is no answer because 14 mod 42 (having a gcd of 14) implies
|
223 |
+
# (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
|
224 |
+
# which, being 0 mod 3, is inconsistent with 1 mod 3. But to
|
225 |
+
# preprocess the input beyond checking of another pair with 42
|
226 |
+
# or 3 as the modulus (for this example) is not necessary.
|
227 |
+
uniq = {}
|
228 |
+
for r, m in rm:
|
229 |
+
r %= m
|
230 |
+
if m in uniq:
|
231 |
+
if r != uniq[m]:
|
232 |
+
return None
|
233 |
+
continue
|
234 |
+
uniq[m] = r
|
235 |
+
rm = [(r, m) for m, r in uniq.items()]
|
236 |
+
del uniq
|
237 |
+
|
238 |
+
# if the moduli are co-prime, the crt will be significantly faster;
|
239 |
+
# checking all pairs for being co-prime gets to be slow but a prime
|
240 |
+
# test is a good trade-off
|
241 |
+
if all(isprime(m) for r, m in rm):
|
242 |
+
r, m = list(zip(*rm))
|
243 |
+
return crt(m, r, symmetric=symmetric, check=False)
|
244 |
+
|
245 |
+
rv = (0, 1)
|
246 |
+
for rmi in rm:
|
247 |
+
rv = combine(rv, rmi)
|
248 |
+
if rv is None:
|
249 |
+
break
|
250 |
+
n, m = rv
|
251 |
+
n = n % m
|
252 |
+
else:
|
253 |
+
if symmetric:
|
254 |
+
return symmetric_residue(n, m), m
|
255 |
+
return n, m
|
venv/lib/python3.10/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.10/site-packages/sympy/ntheory/partitions_.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath.libmp import (fzero, from_int, from_rational,
|
2 |
+
fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub,
|
3 |
+
mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
|
4 |
+
from sympy.core.numbers import igcd
|
5 |
+
from .residue_ntheory import (_sqrt_mod_prime_power,
|
6 |
+
legendre_symbol, jacobi_symbol, is_quad_residue)
|
7 |
+
|
8 |
+
import math
|
9 |
+
|
10 |
+
def _pre():
|
11 |
+
maxn = 10**5
|
12 |
+
global _factor
|
13 |
+
global _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*jacobi_symbol(m - 1, m)),
|
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)*legendre_symbol(m, 3)),
|
79 |
+
mpf_sqrt(from_int(k//3), prec), prec),
|
80 |
+
mpf_sin(arg, prec), prec)
|
81 |
+
v = k + v % k
|
82 |
+
if v % p == 0:
|
83 |
+
if e == 1:
|
84 |
+
return mpf_mul(
|
85 |
+
from_int(jacobi_symbol(3, k)),
|
86 |
+
mpf_sqrt(from_int(k), prec), prec)
|
87 |
+
return fzero
|
88 |
+
if not is_quad_residue(v, p):
|
89 |
+
return fzero
|
90 |
+
_phi = p**(e - 1)*(p - 1)
|
91 |
+
v = (v*pow(576, _phi - 1, k))
|
92 |
+
m = _sqrt_mod_prime_power(v, p, e)[0]
|
93 |
+
arg = mpf_div(
|
94 |
+
mpf_mul(from_int(4*m), pi, prec),
|
95 |
+
from_int(k), prec)
|
96 |
+
return mpf_mul(mpf_mul(
|
97 |
+
from_int(2*jacobi_symbol(3, k)),
|
98 |
+
mpf_sqrt(from_int(k), prec), prec),
|
99 |
+
mpf_cos(arg, prec), prec)
|
100 |
+
|
101 |
+
if p != 2 or e >= 3:
|
102 |
+
d1, d2 = igcd(k1, 24), igcd(k2, 24)
|
103 |
+
e = 24//(d1*d2)
|
104 |
+
n1 = ((d2*e*n + (k2**2 - 1)//d1)*
|
105 |
+
pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
|
106 |
+
n2 = ((d1*e*n + (k1**2 - 1)//d2)*
|
107 |
+
pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
|
108 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
109 |
+
if e == 2:
|
110 |
+
n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
|
111 |
+
n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
|
112 |
+
return mpf_mul(mpf_mul(
|
113 |
+
from_int(-1),
|
114 |
+
_a(n1, k1, prec), prec),
|
115 |
+
_a(n2, k2, prec))
|
116 |
+
n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
|
117 |
+
n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
|
118 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
119 |
+
|
120 |
+
def _d(n, j, prec, sq23pi, sqrt8):
|
121 |
+
"""
|
122 |
+
Compute the sinh term in the outer sum of the HRR formula.
|
123 |
+
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
|
124 |
+
"""
|
125 |
+
j = from_int(j)
|
126 |
+
pi = mpf_pi(prec)
|
127 |
+
a = mpf_div(sq23pi, j, prec)
|
128 |
+
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
|
129 |
+
c = mpf_sqrt(b, prec)
|
130 |
+
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
|
131 |
+
D = mpf_div(
|
132 |
+
mpf_sqrt(j, prec),
|
133 |
+
mpf_mul(mpf_mul(sqrt8, b), pi), prec)
|
134 |
+
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
|
135 |
+
return mpf_mul(D, E)
|
136 |
+
|
137 |
+
|
138 |
+
def npartitions(n, verbose=False):
|
139 |
+
"""
|
140 |
+
Calculate the partition function P(n), i.e. the number of ways that
|
141 |
+
n can be written as a sum of positive integers.
|
142 |
+
|
143 |
+
P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
|
144 |
+
|
145 |
+
|
146 |
+
The correctness of this implementation has been tested through $10^{10}$.
|
147 |
+
|
148 |
+
Examples
|
149 |
+
========
|
150 |
+
|
151 |
+
>>> from sympy.ntheory import npartitions
|
152 |
+
>>> npartitions(25)
|
153 |
+
1958
|
154 |
+
|
155 |
+
References
|
156 |
+
==========
|
157 |
+
|
158 |
+
.. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
|
159 |
+
|
160 |
+
"""
|
161 |
+
n = int(n)
|
162 |
+
if n < 0:
|
163 |
+
return 0
|
164 |
+
if n <= 5:
|
165 |
+
return [1, 1, 2, 3, 5, 7][n]
|
166 |
+
if '_factor' not in globals():
|
167 |
+
_pre()
|
168 |
+
# Estimate number of bits in p(n). This formula could be tidied
|
169 |
+
pbits = int((
|
170 |
+
math.pi*(2*n/3.)**0.5 -
|
171 |
+
math.log(4*n))/math.log(10) + 1) * \
|
172 |
+
math.log(10, 2)
|
173 |
+
prec = p = int(pbits*1.1 + 100)
|
174 |
+
s = fzero
|
175 |
+
M = max(6, int(0.24*n**0.5 + 4))
|
176 |
+
if M > 10**5:
|
177 |
+
raise ValueError("Input too big") # Corresponds to n > 1.7e11
|
178 |
+
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
|
179 |
+
sqrt8 = mpf_sqrt(from_int(8), p)
|
180 |
+
for q in range(1, M):
|
181 |
+
a = _a(n, q, p)
|
182 |
+
d = _d(n, q, p, sq23pi, sqrt8)
|
183 |
+
s = mpf_add(s, mpf_mul(a, d), prec)
|
184 |
+
if verbose:
|
185 |
+
print("step", q, "of", M, to_str(a, 10), to_str(d, 10))
|
186 |
+
# On average, the terms decrease rapidly in magnitude.
|
187 |
+
# Dynamically reducing the precision greatly improves
|
188 |
+
# performance.
|
189 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Primality testing
|
3 |
+
|
4 |
+
"""
|
5 |
+
|
6 |
+
from sympy.core.numbers import igcd
|
7 |
+
from sympy.core.power import integer_nthroot
|
8 |
+
from sympy.core.sympify import sympify
|
9 |
+
from sympy.external.gmpy import HAS_GMPY
|
10 |
+
from sympy.utilities.misc import as_int
|
11 |
+
|
12 |
+
from mpmath.libmp import bitcount as _bitlength
|
13 |
+
|
14 |
+
|
15 |
+
def _int_tuple(*i):
|
16 |
+
return tuple(int(_) for _ in i)
|
17 |
+
|
18 |
+
|
19 |
+
def is_euler_pseudoprime(n, b):
|
20 |
+
"""Returns True if n is prime or an Euler pseudoprime to base b, else False.
|
21 |
+
|
22 |
+
Euler Pseudoprime : In arithmetic, an odd composite integer n is called an
|
23 |
+
euler pseudoprime to base a, if a and n are coprime and satisfy the modular
|
24 |
+
arithmetic congruence relation :
|
25 |
+
|
26 |
+
a ^ (n-1)/2 = + 1(mod n) or
|
27 |
+
a ^ (n-1)/2 = - 1(mod n)
|
28 |
+
|
29 |
+
(where mod refers to the modulo operation).
|
30 |
+
|
31 |
+
Examples
|
32 |
+
========
|
33 |
+
|
34 |
+
>>> from sympy.ntheory.primetest import is_euler_pseudoprime
|
35 |
+
>>> is_euler_pseudoprime(2, 5)
|
36 |
+
True
|
37 |
+
|
38 |
+
References
|
39 |
+
==========
|
40 |
+
|
41 |
+
.. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
|
42 |
+
"""
|
43 |
+
from sympy.ntheory.factor_ import trailing
|
44 |
+
|
45 |
+
if not mr(n, [b]):
|
46 |
+
return False
|
47 |
+
|
48 |
+
n = as_int(n)
|
49 |
+
r = n - 1
|
50 |
+
c = pow(b, r >> trailing(r), n)
|
51 |
+
|
52 |
+
if c == 1:
|
53 |
+
return True
|
54 |
+
|
55 |
+
while True:
|
56 |
+
if c == n - 1:
|
57 |
+
return True
|
58 |
+
c = pow(c, 2, n)
|
59 |
+
if c == 1:
|
60 |
+
return False
|
61 |
+
|
62 |
+
|
63 |
+
def is_square(n, prep=True):
|
64 |
+
"""Return True if n == a * a for some integer a, else False.
|
65 |
+
If n is suspected of *not* being a square then this is a
|
66 |
+
quick method of confirming that it is not.
|
67 |
+
|
68 |
+
Examples
|
69 |
+
========
|
70 |
+
|
71 |
+
>>> from sympy.ntheory.primetest import is_square
|
72 |
+
>>> is_square(25)
|
73 |
+
True
|
74 |
+
>>> is_square(2)
|
75 |
+
False
|
76 |
+
|
77 |
+
References
|
78 |
+
==========
|
79 |
+
|
80 |
+
.. [1] https://mersenneforum.org/showpost.php?p=110896
|
81 |
+
|
82 |
+
See Also
|
83 |
+
========
|
84 |
+
sympy.core.power.integer_nthroot
|
85 |
+
"""
|
86 |
+
if prep:
|
87 |
+
n = as_int(n)
|
88 |
+
if n < 0:
|
89 |
+
return False
|
90 |
+
if n in (0, 1):
|
91 |
+
return True
|
92 |
+
# def magic(n):
|
93 |
+
# s = {x**2 % n for x in range(n)}
|
94 |
+
# return sum(1 << bit for bit in s)
|
95 |
+
# >>> print(hex(magic(128)))
|
96 |
+
# 0x2020212020202130202021202030213
|
97 |
+
# >>> print(hex(magic(99)))
|
98 |
+
# 0x209060049048220348a410213
|
99 |
+
# >>> print(hex(magic(91)))
|
100 |
+
# 0x102e403012a0c9862c14213
|
101 |
+
# >>> print(hex(magic(85)))
|
102 |
+
# 0x121065188e001c46298213
|
103 |
+
if not 0x2020212020202130202021202030213 & (1 << (n & 127)):
|
104 |
+
return False # e.g. 2, 3
|
105 |
+
m = n % (99 * 91 * 85)
|
106 |
+
if not 0x209060049048220348a410213 & (1 << (m % 99)):
|
107 |
+
return False # e.g. 17, 68
|
108 |
+
if not 0x102e403012a0c9862c14213 & (1 << (m % 91)):
|
109 |
+
return False # e.g. 97, 388
|
110 |
+
if not 0x121065188e001c46298213 & (1 << (m % 85)):
|
111 |
+
return False # e.g. 793, 1408
|
112 |
+
# n is either:
|
113 |
+
# a) odd = 4*even + 1 (and square if even = k*(k + 1))
|
114 |
+
# b) even with
|
115 |
+
# odd multiplicity of 2 --> not square, e.g. 39040
|
116 |
+
# even multiplicity of 2, e.g. 4, 16, 36, ..., 16324
|
117 |
+
# removal of factors of 2 to give an odd, and rejection if
|
118 |
+
# any(i%2 for i in divmod(odd - 1, 4))
|
119 |
+
# will give an odd number in form 4*even + 1.
|
120 |
+
# Use of `trailing` to check the power of 2 is not done since it
|
121 |
+
# does not apply to a large percentage of arbitrary numbers
|
122 |
+
# and the integer_nthroot is able to quickly resolve these cases.
|
123 |
+
return integer_nthroot(n, 2)[1]
|
124 |
+
|
125 |
+
|
126 |
+
def _test(n, base, s, t):
|
127 |
+
"""Miller-Rabin strong pseudoprime test for one base.
|
128 |
+
Return False if n is definitely composite, True if n is
|
129 |
+
probably prime, with a probability greater than 3/4.
|
130 |
+
|
131 |
+
"""
|
132 |
+
# do the Fermat test
|
133 |
+
b = pow(base, t, n)
|
134 |
+
if b == 1 or b == n - 1:
|
135 |
+
return True
|
136 |
+
else:
|
137 |
+
for j in range(1, s):
|
138 |
+
b = pow(b, 2, n)
|
139 |
+
if b == n - 1:
|
140 |
+
return True
|
141 |
+
# see I. Niven et al. "An Introduction to Theory of Numbers", page 78
|
142 |
+
if b == 1:
|
143 |
+
return False
|
144 |
+
return False
|
145 |
+
|
146 |
+
|
147 |
+
def mr(n, bases):
|
148 |
+
"""Perform a Miller-Rabin strong pseudoprime test on n using a
|
149 |
+
given list of bases/witnesses.
|
150 |
+
|
151 |
+
References
|
152 |
+
==========
|
153 |
+
|
154 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
155 |
+
A Computational Perspective", Springer, 2nd edition, 135-138
|
156 |
+
|
157 |
+
A list of thresholds and the bases they require are here:
|
158 |
+
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
|
159 |
+
|
160 |
+
Examples
|
161 |
+
========
|
162 |
+
|
163 |
+
>>> from sympy.ntheory.primetest import mr
|
164 |
+
>>> mr(1373651, [2, 3])
|
165 |
+
False
|
166 |
+
>>> mr(479001599, [31, 73])
|
167 |
+
True
|
168 |
+
|
169 |
+
"""
|
170 |
+
from sympy.ntheory.factor_ import trailing
|
171 |
+
from sympy.polys.domains import ZZ
|
172 |
+
|
173 |
+
n = as_int(n)
|
174 |
+
if n < 2:
|
175 |
+
return False
|
176 |
+
# remove powers of 2 from n-1 (= t * 2**s)
|
177 |
+
s = trailing(n - 1)
|
178 |
+
t = n >> s
|
179 |
+
for base in bases:
|
180 |
+
# Bases >= n are wrapped, bases < 2 are invalid
|
181 |
+
if base >= n:
|
182 |
+
base %= n
|
183 |
+
if base >= 2:
|
184 |
+
base = ZZ(base)
|
185 |
+
if not _test(n, base, s, t):
|
186 |
+
return False
|
187 |
+
return True
|
188 |
+
|
189 |
+
|
190 |
+
def _lucas_sequence(n, P, Q, k):
|
191 |
+
"""Return the modular Lucas sequence (U_k, V_k, Q_k).
|
192 |
+
|
193 |
+
Given a Lucas sequence defined by P, Q, returns the kth values for
|
194 |
+
U and V, along with Q^k, all modulo n. This is intended for use with
|
195 |
+
possibly very large values of n and k, where the combinatorial functions
|
196 |
+
would be completely unusable.
|
197 |
+
|
198 |
+
The modular Lucas sequences are used in numerous places in number theory,
|
199 |
+
especially in the Lucas compositeness tests and the various n + 1 proofs.
|
200 |
+
|
201 |
+
Examples
|
202 |
+
========
|
203 |
+
|
204 |
+
>>> from sympy.ntheory.primetest import _lucas_sequence
|
205 |
+
>>> N = 10**2000 + 4561
|
206 |
+
>>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
|
207 |
+
(0, 2, 1)
|
208 |
+
|
209 |
+
"""
|
210 |
+
D = P*P - 4*Q
|
211 |
+
if n < 2:
|
212 |
+
raise ValueError("n must be >= 2")
|
213 |
+
if k < 0:
|
214 |
+
raise ValueError("k must be >= 0")
|
215 |
+
if D == 0:
|
216 |
+
raise ValueError("D must not be zero")
|
217 |
+
|
218 |
+
if k == 0:
|
219 |
+
return _int_tuple(0, 2, Q)
|
220 |
+
U = 1
|
221 |
+
V = P
|
222 |
+
Qk = Q
|
223 |
+
b = _bitlength(k)
|
224 |
+
if Q == 1:
|
225 |
+
# Optimization for extra strong tests.
|
226 |
+
while b > 1:
|
227 |
+
U = (U*V) % n
|
228 |
+
V = (V*V - 2) % n
|
229 |
+
b -= 1
|
230 |
+
if (k >> (b - 1)) & 1:
|
231 |
+
U, V = U*P + V, V*P + U*D
|
232 |
+
if U & 1:
|
233 |
+
U += n
|
234 |
+
if V & 1:
|
235 |
+
V += n
|
236 |
+
U, V = U >> 1, V >> 1
|
237 |
+
elif P == 1 and Q == -1:
|
238 |
+
# Small optimization for 50% of Selfridge parameters.
|
239 |
+
while b > 1:
|
240 |
+
U = (U*V) % n
|
241 |
+
if Qk == 1:
|
242 |
+
V = (V*V - 2) % n
|
243 |
+
else:
|
244 |
+
V = (V*V + 2) % n
|
245 |
+
Qk = 1
|
246 |
+
b -= 1
|
247 |
+
if (k >> (b-1)) & 1:
|
248 |
+
U, V = U + V, V + U*D
|
249 |
+
if U & 1:
|
250 |
+
U += n
|
251 |
+
if V & 1:
|
252 |
+
V += n
|
253 |
+
U, V = U >> 1, V >> 1
|
254 |
+
Qk = -1
|
255 |
+
else:
|
256 |
+
# The general case with any P and Q.
|
257 |
+
while b > 1:
|
258 |
+
U = (U*V) % n
|
259 |
+
V = (V*V - 2*Qk) % n
|
260 |
+
Qk *= Qk
|
261 |
+
b -= 1
|
262 |
+
if (k >> (b - 1)) & 1:
|
263 |
+
U, V = U*P + V, V*P + U*D
|
264 |
+
if U & 1:
|
265 |
+
U += n
|
266 |
+
if V & 1:
|
267 |
+
V += n
|
268 |
+
U, V = U >> 1, V >> 1
|
269 |
+
Qk *= Q
|
270 |
+
Qk %= n
|
271 |
+
return _int_tuple(U % n, V % n, Qk)
|
272 |
+
|
273 |
+
|
274 |
+
def _lucas_selfridge_params(n):
|
275 |
+
"""Calculates the Selfridge parameters (D, P, Q) for n. This is
|
276 |
+
method A from page 1401 of Baillie and Wagstaff.
|
277 |
+
|
278 |
+
References
|
279 |
+
==========
|
280 |
+
.. [1] "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
|
281 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
282 |
+
"""
|
283 |
+
from sympy.ntheory.residue_ntheory import jacobi_symbol
|
284 |
+
D = 5
|
285 |
+
while True:
|
286 |
+
g = igcd(abs(D), n)
|
287 |
+
if g > 1 and g != n:
|
288 |
+
return (0, 0, 0)
|
289 |
+
if jacobi_symbol(D, n) == -1:
|
290 |
+
break
|
291 |
+
if D > 0:
|
292 |
+
D = -D - 2
|
293 |
+
else:
|
294 |
+
D = -D + 2
|
295 |
+
return _int_tuple(D, 1, (1 - D)/4)
|
296 |
+
|
297 |
+
|
298 |
+
def _lucas_extrastrong_params(n):
|
299 |
+
"""Calculates the "extra strong" parameters (D, P, Q) for n.
|
300 |
+
|
301 |
+
References
|
302 |
+
==========
|
303 |
+
.. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
|
304 |
+
https://oeis.org/A217719
|
305 |
+
.. [1] https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
306 |
+
"""
|
307 |
+
from sympy.ntheory.residue_ntheory import jacobi_symbol
|
308 |
+
P, Q, D = 3, 1, 5
|
309 |
+
while True:
|
310 |
+
g = igcd(D, n)
|
311 |
+
if g > 1 and g != n:
|
312 |
+
return (0, 0, 0)
|
313 |
+
if jacobi_symbol(D, n) == -1:
|
314 |
+
break
|
315 |
+
P += 1
|
316 |
+
D = P*P - 4
|
317 |
+
return _int_tuple(D, P, Q)
|
318 |
+
|
319 |
+
|
320 |
+
def is_lucas_prp(n):
|
321 |
+
"""Standard Lucas compositeness test with Selfridge parameters. Returns
|
322 |
+
False if n is definitely composite, and True if n is a Lucas probable
|
323 |
+
prime.
|
324 |
+
|
325 |
+
This is typically used in combination with the Miller-Rabin test.
|
326 |
+
|
327 |
+
References
|
328 |
+
==========
|
329 |
+
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
|
330 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
331 |
+
- OEIS A217120: Lucas Pseudoprimes
|
332 |
+
https://oeis.org/A217120
|
333 |
+
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
334 |
+
|
335 |
+
Examples
|
336 |
+
========
|
337 |
+
|
338 |
+
>>> from sympy.ntheory.primetest import isprime, is_lucas_prp
|
339 |
+
>>> for i in range(10000):
|
340 |
+
... if is_lucas_prp(i) and not isprime(i):
|
341 |
+
... print(i)
|
342 |
+
323
|
343 |
+
377
|
344 |
+
1159
|
345 |
+
1829
|
346 |
+
3827
|
347 |
+
5459
|
348 |
+
5777
|
349 |
+
9071
|
350 |
+
9179
|
351 |
+
"""
|
352 |
+
n = as_int(n)
|
353 |
+
if n == 2:
|
354 |
+
return True
|
355 |
+
if n < 2 or (n % 2) == 0:
|
356 |
+
return False
|
357 |
+
if is_square(n, False):
|
358 |
+
return False
|
359 |
+
|
360 |
+
D, P, Q = _lucas_selfridge_params(n)
|
361 |
+
if D == 0:
|
362 |
+
return False
|
363 |
+
U, V, Qk = _lucas_sequence(n, P, Q, n+1)
|
364 |
+
return U == 0
|
365 |
+
|
366 |
+
|
367 |
+
def is_strong_lucas_prp(n):
|
368 |
+
"""Strong Lucas compositeness test with Selfridge parameters. Returns
|
369 |
+
False if n is definitely composite, and True if n is a strong Lucas
|
370 |
+
probable prime.
|
371 |
+
|
372 |
+
This is often used in combination with the Miller-Rabin test, and
|
373 |
+
in particular, when combined with M-R base 2 creates the strong BPSW test.
|
374 |
+
|
375 |
+
References
|
376 |
+
==========
|
377 |
+
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
|
378 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
379 |
+
- OEIS A217255: Strong Lucas Pseudoprimes
|
380 |
+
https://oeis.org/A217255
|
381 |
+
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
382 |
+
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
|
383 |
+
|
384 |
+
Examples
|
385 |
+
========
|
386 |
+
|
387 |
+
>>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
|
388 |
+
>>> for i in range(20000):
|
389 |
+
... if is_strong_lucas_prp(i) and not isprime(i):
|
390 |
+
... print(i)
|
391 |
+
5459
|
392 |
+
5777
|
393 |
+
10877
|
394 |
+
16109
|
395 |
+
18971
|
396 |
+
"""
|
397 |
+
from sympy.ntheory.factor_ import trailing
|
398 |
+
n = as_int(n)
|
399 |
+
if n == 2:
|
400 |
+
return True
|
401 |
+
if n < 2 or (n % 2) == 0:
|
402 |
+
return False
|
403 |
+
if is_square(n, False):
|
404 |
+
return False
|
405 |
+
|
406 |
+
D, P, Q = _lucas_selfridge_params(n)
|
407 |
+
if D == 0:
|
408 |
+
return False
|
409 |
+
|
410 |
+
# remove powers of 2 from n+1 (= k * 2**s)
|
411 |
+
s = trailing(n + 1)
|
412 |
+
k = (n+1) >> s
|
413 |
+
|
414 |
+
U, V, Qk = _lucas_sequence(n, P, Q, k)
|
415 |
+
|
416 |
+
if U == 0 or V == 0:
|
417 |
+
return True
|
418 |
+
for r in range(1, s):
|
419 |
+
V = (V*V - 2*Qk) % n
|
420 |
+
if V == 0:
|
421 |
+
return True
|
422 |
+
Qk = pow(Qk, 2, n)
|
423 |
+
return False
|
424 |
+
|
425 |
+
|
426 |
+
def is_extra_strong_lucas_prp(n):
|
427 |
+
"""Extra Strong Lucas compositeness test. Returns False if n is
|
428 |
+
definitely composite, and True if n is a "extra strong" Lucas probable
|
429 |
+
prime.
|
430 |
+
|
431 |
+
The parameters are selected using P = 3, Q = 1, then incrementing P until
|
432 |
+
(D|n) == -1. The test itself is as defined in Grantham 2000, from the
|
433 |
+
Mo and Jones preprint. The parameter selection and test are the same as
|
434 |
+
used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
|
435 |
+
page on Wikipedia.
|
436 |
+
|
437 |
+
With these parameters, there are no counterexamples below 2^64 nor any
|
438 |
+
known above that range. It is 20-50% faster than the strong test.
|
439 |
+
|
440 |
+
Because of the different parameters selected, there is no relationship
|
441 |
+
between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
|
442 |
+
In particular, one is not a subset of the other.
|
443 |
+
|
444 |
+
References
|
445 |
+
==========
|
446 |
+
- "Frobenius Pseudoprimes", Jon Grantham, 2000.
|
447 |
+
https://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/
|
448 |
+
- OEIS A217719: Extra Strong Lucas Pseudoprimes
|
449 |
+
https://oeis.org/A217719
|
450 |
+
- https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
451 |
+
|
452 |
+
Examples
|
453 |
+
========
|
454 |
+
|
455 |
+
>>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
|
456 |
+
>>> for i in range(20000):
|
457 |
+
... if is_extra_strong_lucas_prp(i) and not isprime(i):
|
458 |
+
... print(i)
|
459 |
+
989
|
460 |
+
3239
|
461 |
+
5777
|
462 |
+
10877
|
463 |
+
"""
|
464 |
+
# Implementation notes:
|
465 |
+
# 1) the parameters differ from Thomas R. Nicely's. His parameter
|
466 |
+
# selection leads to pseudoprimes that overlap M-R tests, and
|
467 |
+
# contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
|
468 |
+
# 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
|
469 |
+
# sequence must have Q=1. See Grantham theorem 2.3, any of the
|
470 |
+
# references on the MathWorld page, or run it and see Q=-1 is wrong.
|
471 |
+
from sympy.ntheory.factor_ import trailing
|
472 |
+
n = as_int(n)
|
473 |
+
if n == 2:
|
474 |
+
return True
|
475 |
+
if n < 2 or (n % 2) == 0:
|
476 |
+
return False
|
477 |
+
if is_square(n, False):
|
478 |
+
return False
|
479 |
+
|
480 |
+
D, P, Q = _lucas_extrastrong_params(n)
|
481 |
+
if D == 0:
|
482 |
+
return False
|
483 |
+
|
484 |
+
# remove powers of 2 from n+1 (= k * 2**s)
|
485 |
+
s = trailing(n + 1)
|
486 |
+
k = (n+1) >> s
|
487 |
+
|
488 |
+
U, V, Qk = _lucas_sequence(n, P, Q, k)
|
489 |
+
|
490 |
+
if U == 0 and (V == 2 or V == n - 2):
|
491 |
+
return True
|
492 |
+
for r in range(1, s):
|
493 |
+
if V == 0:
|
494 |
+
return True
|
495 |
+
V = (V*V - 2) % n
|
496 |
+
return False
|
497 |
+
|
498 |
+
|
499 |
+
def isprime(n):
|
500 |
+
"""
|
501 |
+
Test if n is a prime number (True) or not (False). For n < 2^64 the
|
502 |
+
answer is definitive; larger n values have a small probability of actually
|
503 |
+
being pseudoprimes.
|
504 |
+
|
505 |
+
Negative numbers (e.g. -2) are not considered prime.
|
506 |
+
|
507 |
+
The first step is looking for trivial factors, which if found enables
|
508 |
+
a quick return. Next, if the sieve is large enough, use bisection search
|
509 |
+
on the sieve. For small numbers, a set of deterministic Miller-Rabin
|
510 |
+
tests are performed with bases that are known to have no counterexamples
|
511 |
+
in their range. Finally if the number is larger than 2^64, a strong
|
512 |
+
BPSW test is performed. While this is a probable prime test and we
|
513 |
+
believe counterexamples exist, there are no known counterexamples.
|
514 |
+
|
515 |
+
Examples
|
516 |
+
========
|
517 |
+
|
518 |
+
>>> from sympy.ntheory import isprime
|
519 |
+
>>> isprime(13)
|
520 |
+
True
|
521 |
+
>>> isprime(13.0) # limited precision
|
522 |
+
False
|
523 |
+
>>> isprime(15)
|
524 |
+
False
|
525 |
+
|
526 |
+
Notes
|
527 |
+
=====
|
528 |
+
|
529 |
+
This routine is intended only for integer input, not numerical
|
530 |
+
expressions which may represent numbers. Floats are also
|
531 |
+
rejected as input because they represent numbers of limited
|
532 |
+
precision. While it is tempting to permit 7.0 to represent an
|
533 |
+
integer there are errors that may "pass silently" if this is
|
534 |
+
allowed:
|
535 |
+
|
536 |
+
>>> from sympy import Float, S
|
537 |
+
>>> int(1e3) == 1e3 == 10**3
|
538 |
+
True
|
539 |
+
>>> int(1e23) == 1e23
|
540 |
+
True
|
541 |
+
>>> int(1e23) == 10**23
|
542 |
+
False
|
543 |
+
|
544 |
+
>>> near_int = 1 + S(1)/10**19
|
545 |
+
>>> near_int == int(near_int)
|
546 |
+
False
|
547 |
+
>>> n = Float(near_int, 10) # truncated by precision
|
548 |
+
>>> n == int(n)
|
549 |
+
True
|
550 |
+
>>> n = Float(near_int, 20)
|
551 |
+
>>> n == int(n)
|
552 |
+
False
|
553 |
+
|
554 |
+
See Also
|
555 |
+
========
|
556 |
+
|
557 |
+
sympy.ntheory.generate.primerange : Generates all primes in a given range
|
558 |
+
sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n
|
559 |
+
sympy.ntheory.generate.prime : Return the nth prime
|
560 |
+
|
561 |
+
References
|
562 |
+
==========
|
563 |
+
- https://en.wikipedia.org/wiki/Strong_pseudoprime
|
564 |
+
- "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
|
565 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
566 |
+
- https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
|
567 |
+
"""
|
568 |
+
try:
|
569 |
+
n = as_int(n)
|
570 |
+
except ValueError:
|
571 |
+
return False
|
572 |
+
|
573 |
+
# Step 1, do quick composite testing via trial division. The individual
|
574 |
+
# modulo tests benchmark faster than one or two primorial igcds for me.
|
575 |
+
# The point here is just to speedily handle small numbers and many
|
576 |
+
# composites. Step 2 only requires that n <= 2 get handled here.
|
577 |
+
if n in [2, 3, 5]:
|
578 |
+
return True
|
579 |
+
if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
|
580 |
+
return False
|
581 |
+
if n < 49:
|
582 |
+
return True
|
583 |
+
if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
|
584 |
+
(n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
|
585 |
+
(n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
|
586 |
+
return False
|
587 |
+
if n < 2809:
|
588 |
+
return True
|
589 |
+
if n < 31417:
|
590 |
+
return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951, 23377]
|
591 |
+
|
592 |
+
# bisection search on the sieve if the sieve is large enough
|
593 |
+
from sympy.ntheory.generate import sieve as s
|
594 |
+
if n <= s._list[-1]:
|
595 |
+
l, u = s.search(n)
|
596 |
+
return l == u
|
597 |
+
|
598 |
+
# If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
|
599 |
+
# This should be a bit faster than our step 2, and for large values will
|
600 |
+
# be a lot faster than our step 3 (C+GMP vs. Python).
|
601 |
+
if HAS_GMPY == 2:
|
602 |
+
from gmpy2 import is_strong_prp, is_strong_selfridge_prp
|
603 |
+
return is_strong_prp(n, 2) and is_strong_selfridge_prp(n)
|
604 |
+
|
605 |
+
|
606 |
+
# Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
|
607 |
+
# https://miller-rabin.appspot.com/
|
608 |
+
# for lists. We have made sure the M-R routine will successfully handle
|
609 |
+
# bases larger than n, so we can use the minimal set.
|
610 |
+
# In September 2015 deterministic numbers were extended to over 2^81.
|
611 |
+
# https://arxiv.org/pdf/1509.00864.pdf
|
612 |
+
# https://oeis.org/A014233
|
613 |
+
if n < 341531:
|
614 |
+
return mr(n, [9345883071009581737])
|
615 |
+
if n < 885594169:
|
616 |
+
return mr(n, [725270293939359937, 3569819667048198375])
|
617 |
+
if n < 350269456337:
|
618 |
+
return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
|
619 |
+
if n < 55245642489451:
|
620 |
+
return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
|
621 |
+
if n < 7999252175582851:
|
622 |
+
return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
|
623 |
+
if n < 585226005592931977:
|
624 |
+
return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
|
625 |
+
if n < 18446744073709551616:
|
626 |
+
return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
|
627 |
+
if n < 318665857834031151167461:
|
628 |
+
return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
|
629 |
+
if n < 3317044064679887385961981:
|
630 |
+
return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
|
631 |
+
|
632 |
+
# We could do this instead at any point:
|
633 |
+
#if n < 18446744073709551616:
|
634 |
+
# return mr(n, [2]) and is_extra_strong_lucas_prp(n)
|
635 |
+
|
636 |
+
# Here are tests that are safe for MR routines that don't understand
|
637 |
+
# large bases.
|
638 |
+
#if n < 9080191:
|
639 |
+
# return mr(n, [31, 73])
|
640 |
+
#if n < 19471033:
|
641 |
+
# return mr(n, [2, 299417])
|
642 |
+
#if n < 38010307:
|
643 |
+
# return mr(n, [2, 9332593])
|
644 |
+
#if n < 316349281:
|
645 |
+
# return mr(n, [11000544, 31481107])
|
646 |
+
#if n < 4759123141:
|
647 |
+
# return mr(n, [2, 7, 61])
|
648 |
+
#if n < 105936894253:
|
649 |
+
# return mr(n, [2, 1005905886, 1340600841])
|
650 |
+
#if n < 31858317218647:
|
651 |
+
# return mr(n, [2, 642735, 553174392, 3046413974])
|
652 |
+
#if n < 3071837692357849:
|
653 |
+
# return mr(n, [2, 75088, 642735, 203659041, 3613982119])
|
654 |
+
#if n < 18446744073709551616:
|
655 |
+
# return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
|
656 |
+
|
657 |
+
# Step 3: BPSW.
|
658 |
+
#
|
659 |
+
# Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
|
660 |
+
# 44.0s old isprime using 46 bases
|
661 |
+
# 5.3s strong BPSW + one random base
|
662 |
+
# 4.3s extra strong BPSW + one random base
|
663 |
+
# 4.1s strong BPSW
|
664 |
+
# 3.2s extra strong BPSW
|
665 |
+
|
666 |
+
# Classic BPSW from page 1401 of the paper. See alternate ideas below.
|
667 |
+
return mr(n, [2]) and is_strong_lucas_prp(n)
|
668 |
+
|
669 |
+
# Using extra strong test, which is somewhat faster
|
670 |
+
#return mr(n, [2]) and is_extra_strong_lucas_prp(n)
|
671 |
+
|
672 |
+
# Add a random M-R base
|
673 |
+
#import random
|
674 |
+
#return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
|
675 |
+
|
676 |
+
|
677 |
+
def is_gaussian_prime(num):
|
678 |
+
r"""Test if num is a Gaussian prime number.
|
679 |
+
|
680 |
+
References
|
681 |
+
==========
|
682 |
+
|
683 |
+
.. [1] https://oeis.org/wiki/Gaussian_primes
|
684 |
+
"""
|
685 |
+
|
686 |
+
num = sympify(num)
|
687 |
+
a, b = num.as_real_imag()
|
688 |
+
a = as_int(a, strict=False)
|
689 |
+
b = as_int(b, strict=False)
|
690 |
+
if a == 0:
|
691 |
+
b = abs(b)
|
692 |
+
return isprime(b) and b % 4 == 3
|
693 |
+
elif b == 0:
|
694 |
+
a = abs(a)
|
695 |
+
return isprime(a) and a % 4 == 3
|
696 |
+
return isprime(a**2 + b**2)
|
venv/lib/python3.10/site-packages/sympy/ntheory/qs.py
ADDED
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import igcd, mod_inverse
|
2 |
+
from sympy.core.power import integer_nthroot
|
3 |
+
from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
|
4 |
+
from sympy.ntheory import isprime
|
5 |
+
from math import log, sqrt
|
6 |
+
import random
|
7 |
+
|
8 |
+
rgen = random.Random()
|
9 |
+
|
10 |
+
class SievePolynomial:
|
11 |
+
def __init__(self, modified_coeff=(), a=None, b=None):
|
12 |
+
"""This class denotes the seive polynomial.
|
13 |
+
If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded
|
14 |
+
to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient
|
15 |
+
is stored in the form `[a**2, 2*a*b, b**2 - N]`. This
|
16 |
+
ensures faster `eval` method because we dont have to
|
17 |
+
perform `a**2, 2*a*b, b**2` every time we call the
|
18 |
+
`eval` method. As multiplication is more expensive
|
19 |
+
than addition, by using modified_coefficient we get
|
20 |
+
a faster seiving process.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
==========
|
24 |
+
|
25 |
+
modified_coeff : modified_coefficient of sieve polynomial
|
26 |
+
a : parameter of the sieve polynomial
|
27 |
+
b : parameter of the sieve polynomial
|
28 |
+
"""
|
29 |
+
self.modified_coeff = modified_coeff
|
30 |
+
self.a = a
|
31 |
+
self.b = b
|
32 |
+
|
33 |
+
def eval(self, x):
|
34 |
+
"""
|
35 |
+
Compute the value of the sieve polynomial at point x.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
==========
|
39 |
+
|
40 |
+
x : Integer parameter for sieve polynomial
|
41 |
+
"""
|
42 |
+
ans = 0
|
43 |
+
for coeff in self.modified_coeff:
|
44 |
+
ans *= x
|
45 |
+
ans += coeff
|
46 |
+
return ans
|
47 |
+
|
48 |
+
|
49 |
+
class FactorBaseElem:
|
50 |
+
"""This class stores an element of the `factor_base`.
|
51 |
+
"""
|
52 |
+
def __init__(self, prime, tmem_p, log_p):
|
53 |
+
"""
|
54 |
+
Initialization of factor_base_elem.
|
55 |
+
|
56 |
+
Parameters
|
57 |
+
==========
|
58 |
+
|
59 |
+
prime : prime number of the factor_base
|
60 |
+
tmem_p : Integer square root of x**2 = n mod prime
|
61 |
+
log_p : Compute Natural Logarithm of the prime
|
62 |
+
"""
|
63 |
+
self.prime = prime
|
64 |
+
self.tmem_p = tmem_p
|
65 |
+
self.log_p = log_p
|
66 |
+
self.soln1 = None
|
67 |
+
self.soln2 = None
|
68 |
+
self.a_inv = None
|
69 |
+
self.b_ainv = None
|
70 |
+
|
71 |
+
|
72 |
+
def _generate_factor_base(prime_bound, n):
|
73 |
+
"""Generate `factor_base` for Quadratic Sieve. The `factor_base`
|
74 |
+
consists of all the points whose ``legendre_symbol(n, p) == 1``
|
75 |
+
and ``p < num_primes``. Along with the prime `factor_base` also stores
|
76 |
+
natural logarithm of prime and the residue n modulo p.
|
77 |
+
It also returns the of primes numbers in the `factor_base` which are
|
78 |
+
close to 1000 and 5000.
|
79 |
+
|
80 |
+
Parameters
|
81 |
+
==========
|
82 |
+
|
83 |
+
prime_bound : upper prime bound of the factor_base
|
84 |
+
n : integer to be factored
|
85 |
+
"""
|
86 |
+
from sympy.ntheory.generate import sieve
|
87 |
+
factor_base = []
|
88 |
+
idx_1000, idx_5000 = None, None
|
89 |
+
for prime in sieve.primerange(1, prime_bound):
|
90 |
+
if pow(n, (prime - 1) // 2, prime) == 1:
|
91 |
+
if prime > 1000 and idx_1000 is None:
|
92 |
+
idx_1000 = len(factor_base) - 1
|
93 |
+
if prime > 5000 and idx_5000 is None:
|
94 |
+
idx_5000 = len(factor_base) - 1
|
95 |
+
residue = _sqrt_mod_prime_power(n, prime, 1)[0]
|
96 |
+
log_p = round(log(prime)*2**10)
|
97 |
+
factor_base.append(FactorBaseElem(prime, residue, log_p))
|
98 |
+
return idx_1000, idx_5000, factor_base
|
99 |
+
|
100 |
+
|
101 |
+
def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None):
|
102 |
+
"""This step is the initialization of the 1st sieve polynomial.
|
103 |
+
Here `a` is selected as a product of several primes of the factor_base
|
104 |
+
such that `a` is about to ``sqrt(2*N) / M``. Other initial values of
|
105 |
+
factor_base elem are also initialized which includes a_inv, b_ainv, soln1,
|
106 |
+
soln2 which are used when the sieve polynomial is changed. The b_ainv
|
107 |
+
is required for fast polynomial change as we do not have to calculate
|
108 |
+
`2*b*mod_inverse(a, prime)` every time.
|
109 |
+
We also ensure that the `factor_base` primes which make `a` are between
|
110 |
+
1000 and 5000.
|
111 |
+
|
112 |
+
Parameters
|
113 |
+
==========
|
114 |
+
|
115 |
+
N : Number to be factored
|
116 |
+
M : sieve interval
|
117 |
+
factor_base : factor_base primes
|
118 |
+
idx_1000 : index of prime number in the factor_base near 1000
|
119 |
+
idx_5000 : index of prime number in the factor_base near to 5000
|
120 |
+
seed : Generate pseudoprime numbers
|
121 |
+
"""
|
122 |
+
if seed is not None:
|
123 |
+
rgen.seed(seed)
|
124 |
+
approx_val = sqrt(2*N) / M
|
125 |
+
# `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a`
|
126 |
+
# randomly search for a combination of primes whose multiplication is close to approx_val
|
127 |
+
# This multiplication of primes will be `a` and the primes will be `q`
|
128 |
+
# `best_a` denotes that `a` is close to approx_val in the random search of combination
|
129 |
+
best_a, best_q, best_ratio = None, None, None
|
130 |
+
start = 0 if idx_1000 is None else idx_1000
|
131 |
+
end = len(factor_base) - 1 if idx_5000 is None else idx_5000
|
132 |
+
for _ in range(50):
|
133 |
+
a = 1
|
134 |
+
q = []
|
135 |
+
while(a < approx_val):
|
136 |
+
rand_p = 0
|
137 |
+
while(rand_p == 0 or rand_p in q):
|
138 |
+
rand_p = rgen.randint(start, end)
|
139 |
+
p = factor_base[rand_p].prime
|
140 |
+
a *= p
|
141 |
+
q.append(rand_p)
|
142 |
+
ratio = a / approx_val
|
143 |
+
if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
|
144 |
+
best_q = q
|
145 |
+
best_a = a
|
146 |
+
best_ratio = ratio
|
147 |
+
|
148 |
+
a = best_a
|
149 |
+
q = best_q
|
150 |
+
|
151 |
+
B = []
|
152 |
+
for idx, val in enumerate(q):
|
153 |
+
q_l = factor_base[val].prime
|
154 |
+
gamma = factor_base[val].tmem_p * mod_inverse(a // q_l, q_l) % q_l
|
155 |
+
if gamma > q_l / 2:
|
156 |
+
gamma = q_l - gamma
|
157 |
+
B.append(a//q_l*gamma)
|
158 |
+
|
159 |
+
b = sum(B)
|
160 |
+
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
|
161 |
+
|
162 |
+
for fb in factor_base:
|
163 |
+
if a % fb.prime == 0:
|
164 |
+
continue
|
165 |
+
fb.a_inv = mod_inverse(a, fb.prime)
|
166 |
+
fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B]
|
167 |
+
fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime
|
168 |
+
fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime
|
169 |
+
return g, B
|
170 |
+
|
171 |
+
|
172 |
+
def _initialize_ith_poly(N, factor_base, i, g, B):
|
173 |
+
"""Initialization stage of ith poly. After we finish sieving 1`st polynomial
|
174 |
+
here we quickly change to the next polynomial from which we will again
|
175 |
+
start sieving. Suppose we generated ith sieve polynomial and now we
|
176 |
+
want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1``
|
177 |
+
where `j` is the number of prime factors of the coefficient `a`
|
178 |
+
then this function can be used to go to the next polynomial. If
|
179 |
+
``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage.
|
180 |
+
|
181 |
+
Parameters
|
182 |
+
==========
|
183 |
+
|
184 |
+
N : number to be factored
|
185 |
+
factor_base : factor_base primes
|
186 |
+
i : integer denoting ith polynomial
|
187 |
+
g : (i - 1)th polynomial
|
188 |
+
B : array that stores a//q_l*gamma
|
189 |
+
"""
|
190 |
+
from sympy.functions.elementary.integers import ceiling
|
191 |
+
v = 1
|
192 |
+
j = i
|
193 |
+
while(j % 2 == 0):
|
194 |
+
v += 1
|
195 |
+
j //= 2
|
196 |
+
if ceiling(i / (2**v)) % 2 == 1:
|
197 |
+
neg_pow = -1
|
198 |
+
else:
|
199 |
+
neg_pow = 1
|
200 |
+
b = g.b + 2*neg_pow*B[v - 1]
|
201 |
+
a = g.a
|
202 |
+
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
|
203 |
+
for fb in factor_base:
|
204 |
+
if a % fb.prime == 0:
|
205 |
+
continue
|
206 |
+
fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
|
207 |
+
fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
|
208 |
+
|
209 |
+
return g
|
210 |
+
|
211 |
+
|
212 |
+
def _gen_sieve_array(M, factor_base):
|
213 |
+
"""Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
|
214 |
+
that does not divide the coefficient `a` we add log_p over the sieve_array
|
215 |
+
such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
|
216 |
+
is an integer. When p = 2 then log_p is only added using
|
217 |
+
``-M <= soln1 + i*p <= M``.
|
218 |
+
|
219 |
+
Parameters
|
220 |
+
==========
|
221 |
+
|
222 |
+
M : sieve interval
|
223 |
+
factor_base : factor_base primes
|
224 |
+
"""
|
225 |
+
sieve_array = [0]*(2*M + 1)
|
226 |
+
for factor in factor_base:
|
227 |
+
if factor.soln1 is None: #The prime does not divides a
|
228 |
+
continue
|
229 |
+
for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
|
230 |
+
sieve_array[idx] += factor.log_p
|
231 |
+
if factor.prime == 2:
|
232 |
+
continue
|
233 |
+
#if prime is 2 then sieve only with soln_1_p
|
234 |
+
for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
|
235 |
+
sieve_array[idx] += factor.log_p
|
236 |
+
return sieve_array
|
237 |
+
|
238 |
+
|
239 |
+
def _check_smoothness(num, factor_base):
|
240 |
+
"""Here we check that if `num` is a smooth number or not. If `a` is a smooth
|
241 |
+
number then it returns a vector of prime exponents modulo 2. For example
|
242 |
+
if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then
|
243 |
+
`a` is a smooth number and this function returns ([1, 0, 0, 1], True). If
|
244 |
+
`a` is a partial relation which means that `a` a has one prime factor
|
245 |
+
greater than the `factor_base` then it returns `(a, False)` which denotes `a`
|
246 |
+
is a partial relation.
|
247 |
+
|
248 |
+
Parameters
|
249 |
+
==========
|
250 |
+
|
251 |
+
a : integer whose smootheness is to be checked
|
252 |
+
factor_base : factor_base primes
|
253 |
+
"""
|
254 |
+
vec = []
|
255 |
+
if num < 0:
|
256 |
+
vec.append(1)
|
257 |
+
num *= -1
|
258 |
+
else:
|
259 |
+
vec.append(0)
|
260 |
+
#-1 is not included in factor_base add -1 in vector
|
261 |
+
for factor in factor_base:
|
262 |
+
if num % factor.prime != 0:
|
263 |
+
vec.append(0)
|
264 |
+
continue
|
265 |
+
factor_exp = 0
|
266 |
+
while num % factor.prime == 0:
|
267 |
+
factor_exp += 1
|
268 |
+
num //= factor.prime
|
269 |
+
vec.append(factor_exp % 2)
|
270 |
+
if num == 1:
|
271 |
+
return vec, True
|
272 |
+
if isprime(num):
|
273 |
+
return num, False
|
274 |
+
return None, None
|
275 |
+
|
276 |
+
|
277 |
+
def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
|
278 |
+
"""Trial division stage. Here we trial divide the values generetated
|
279 |
+
by sieve_poly in the sieve interval and if it is a smooth number then
|
280 |
+
it is stored in `smooth_relations`. Moreover, if we find two partial relations
|
281 |
+
with same large prime then they are combined to form a smooth relation.
|
282 |
+
First we iterate over sieve array and look for values which are greater
|
283 |
+
than accumulated_val, as these values have a high chance of being smooth
|
284 |
+
number. Then using these values we find smooth relations.
|
285 |
+
In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
|
286 |
+
with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
|
287 |
+
to form a smooth relation.
|
288 |
+
|
289 |
+
Parameters
|
290 |
+
==========
|
291 |
+
|
292 |
+
N : Number to be factored
|
293 |
+
M : sieve interval
|
294 |
+
factor_base : factor_base primes
|
295 |
+
sieve_array : stores log_p values
|
296 |
+
sieve_poly : polynomial from which we find smooth relations
|
297 |
+
partial_relations : stores partial relations with one large prime
|
298 |
+
ERROR_TERM : error term for accumulated_val
|
299 |
+
"""
|
300 |
+
sqrt_n = sqrt(float(N))
|
301 |
+
accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM
|
302 |
+
smooth_relations = []
|
303 |
+
proper_factor = set()
|
304 |
+
partial_relation_upper_bound = 128*factor_base[-1].prime
|
305 |
+
for idx, val in enumerate(sieve_array):
|
306 |
+
if val < accumulated_val:
|
307 |
+
continue
|
308 |
+
x = idx - M
|
309 |
+
v = sieve_poly.eval(x)
|
310 |
+
vec, is_smooth = _check_smoothness(v, factor_base)
|
311 |
+
if is_smooth is None:#Neither smooth nor partial
|
312 |
+
continue
|
313 |
+
u = sieve_poly.a*x + sieve_poly.b
|
314 |
+
# Update the partial relation
|
315 |
+
# If 2 partial relation with same large prime is found then generate smooth relation
|
316 |
+
if is_smooth is False:#partial relation found
|
317 |
+
large_prime = vec
|
318 |
+
#Consider the large_primes under 128*F
|
319 |
+
if large_prime > partial_relation_upper_bound:
|
320 |
+
continue
|
321 |
+
if large_prime not in partial_relations:
|
322 |
+
partial_relations[large_prime] = (u, v)
|
323 |
+
continue
|
324 |
+
else:
|
325 |
+
u_prev, v_prev = partial_relations[large_prime]
|
326 |
+
partial_relations.pop(large_prime)
|
327 |
+
try:
|
328 |
+
large_prime_inv = mod_inverse(large_prime, N)
|
329 |
+
except ValueError:#if large_prine divides N
|
330 |
+
proper_factor.add(large_prime)
|
331 |
+
continue
|
332 |
+
u = u*u_prev*large_prime_inv
|
333 |
+
v = v*v_prev // (large_prime*large_prime)
|
334 |
+
vec, is_smooth = _check_smoothness(v, factor_base)
|
335 |
+
#assert u*u % N == v % N
|
336 |
+
smooth_relations.append((u, v, vec))
|
337 |
+
return smooth_relations, proper_factor
|
338 |
+
|
339 |
+
|
340 |
+
#LINEAR ALGEBRA STAGE
|
341 |
+
def _build_matrix(smooth_relations):
|
342 |
+
"""Build a 2D matrix from smooth relations.
|
343 |
+
|
344 |
+
Parameters
|
345 |
+
==========
|
346 |
+
|
347 |
+
smooth_relations : Stores smooth relations
|
348 |
+
"""
|
349 |
+
matrix = []
|
350 |
+
for s_relation in smooth_relations:
|
351 |
+
matrix.append(s_relation[2])
|
352 |
+
return matrix
|
353 |
+
|
354 |
+
|
355 |
+
def _gauss_mod_2(A):
|
356 |
+
"""Fast gaussian reduction for modulo 2 matrix.
|
357 |
+
|
358 |
+
Parameters
|
359 |
+
==========
|
360 |
+
|
361 |
+
A : Matrix
|
362 |
+
|
363 |
+
Examples
|
364 |
+
========
|
365 |
+
|
366 |
+
>>> from sympy.ntheory.qs import _gauss_mod_2
|
367 |
+
>>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]])
|
368 |
+
([[[1, 0, 1], 3]],
|
369 |
+
[True, True, True, False],
|
370 |
+
[[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]])
|
371 |
+
|
372 |
+
Reference
|
373 |
+
==========
|
374 |
+
|
375 |
+
.. [1] A fast algorithm for gaussian elimination over GF(2) and
|
376 |
+
its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige"""
|
377 |
+
import copy
|
378 |
+
matrix = copy.deepcopy(A)
|
379 |
+
row = len(matrix)
|
380 |
+
col = len(matrix[0])
|
381 |
+
mark = [False]*row
|
382 |
+
for c in range(col):
|
383 |
+
for r in range(row):
|
384 |
+
if matrix[r][c] == 1:
|
385 |
+
break
|
386 |
+
mark[r] = True
|
387 |
+
for c1 in range(col):
|
388 |
+
if c1 == c:
|
389 |
+
continue
|
390 |
+
if matrix[r][c1] == 1:
|
391 |
+
for r2 in range(row):
|
392 |
+
matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2
|
393 |
+
dependent_row = []
|
394 |
+
for idx, val in enumerate(mark):
|
395 |
+
if val == False:
|
396 |
+
dependent_row.append([matrix[idx], idx])
|
397 |
+
return dependent_row, mark, matrix
|
398 |
+
|
399 |
+
|
400 |
+
def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N):
|
401 |
+
"""Finds proper factor of N. Here, transform the dependent rows as a
|
402 |
+
combination of independent rows of the gauss_matrix to form the desired
|
403 |
+
relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation
|
404 |
+
we obtain a proper factor of N by `gcd(X - Y, N)`.
|
405 |
+
|
406 |
+
Parameters
|
407 |
+
==========
|
408 |
+
|
409 |
+
dependent_rows : denoted dependent rows in the reduced matrix form
|
410 |
+
mark : boolean array to denoted dependent and independent rows
|
411 |
+
gauss_matrix : Reduced form of the smooth relations matrix
|
412 |
+
index : denoted the index of the dependent_rows
|
413 |
+
smooth_relations : Smooth relations vectors matrix
|
414 |
+
N : Number to be factored
|
415 |
+
"""
|
416 |
+
idx_in_smooth = dependent_rows[index][1]
|
417 |
+
independent_u = [smooth_relations[idx_in_smooth][0]]
|
418 |
+
independent_v = [smooth_relations[idx_in_smooth][1]]
|
419 |
+
dept_row = dependent_rows[index][0]
|
420 |
+
|
421 |
+
for idx, val in enumerate(dept_row):
|
422 |
+
if val == 1:
|
423 |
+
for row in range(len(gauss_matrix)):
|
424 |
+
if gauss_matrix[row][idx] == 1 and mark[row] == True:
|
425 |
+
independent_u.append(smooth_relations[row][0])
|
426 |
+
independent_v.append(smooth_relations[row][1])
|
427 |
+
break
|
428 |
+
|
429 |
+
u = 1
|
430 |
+
v = 1
|
431 |
+
for i in independent_u:
|
432 |
+
u *= i
|
433 |
+
for i in independent_v:
|
434 |
+
v *= i
|
435 |
+
#assert u**2 % N == v % N
|
436 |
+
v = integer_nthroot(v, 2)[0]
|
437 |
+
return igcd(u - v, N)
|
438 |
+
|
439 |
+
|
440 |
+
def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
|
441 |
+
"""Performs factorization using Self-Initializing Quadratic Sieve.
|
442 |
+
In SIQS, let N be a number to be factored, and this N should not be a
|
443 |
+
perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
|
444 |
+
``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
|
445 |
+
In order to find these integers X and Y we try to find relations of form
|
446 |
+
t**2 = u modN where u is a product of small primes. If we have enough of
|
447 |
+
these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
|
448 |
+
the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
|
449 |
+
|
450 |
+
Here, several optimizations are done like using multiple polynomials for
|
451 |
+
sieving, fast changing between polynomials and using partial relations.
|
452 |
+
The use of partial relations can speeds up the factoring by 2 times.
|
453 |
+
|
454 |
+
Parameters
|
455 |
+
==========
|
456 |
+
|
457 |
+
N : Number to be Factored
|
458 |
+
prime_bound : upper bound for primes in the factor base
|
459 |
+
M : Sieve Interval
|
460 |
+
ERROR_TERM : Error term for checking smoothness
|
461 |
+
threshold : Extra smooth relations for factorization
|
462 |
+
seed : generate pseudo prime numbers
|
463 |
+
|
464 |
+
Examples
|
465 |
+
========
|
466 |
+
|
467 |
+
>>> from sympy.ntheory import qs
|
468 |
+
>>> qs(25645121643901801, 2000, 10000)
|
469 |
+
{5394769, 4753701529}
|
470 |
+
>>> qs(9804659461513846513, 2000, 10000)
|
471 |
+
{4641991, 2112166839943}
|
472 |
+
|
473 |
+
References
|
474 |
+
==========
|
475 |
+
|
476 |
+
.. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
|
477 |
+
.. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
|
478 |
+
"""
|
479 |
+
ERROR_TERM*=2**10
|
480 |
+
rgen.seed(seed)
|
481 |
+
idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
|
482 |
+
smooth_relations = []
|
483 |
+
ith_poly = 0
|
484 |
+
partial_relations = {}
|
485 |
+
proper_factor = set()
|
486 |
+
threshold = 5*len(factor_base) // 100
|
487 |
+
while True:
|
488 |
+
if ith_poly == 0:
|
489 |
+
ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000)
|
490 |
+
else:
|
491 |
+
ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array)
|
492 |
+
ith_poly += 1
|
493 |
+
if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial
|
494 |
+
ith_poly = 0
|
495 |
+
sieve_array = _gen_sieve_array(M, factor_base)
|
496 |
+
s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM)
|
497 |
+
smooth_relations += s_rel
|
498 |
+
proper_factor |= p_f
|
499 |
+
if len(smooth_relations) >= len(factor_base) + threshold:
|
500 |
+
break
|
501 |
+
matrix = _build_matrix(smooth_relations)
|
502 |
+
dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix)
|
503 |
+
N_copy = N
|
504 |
+
for index in range(len(dependent_row)):
|
505 |
+
factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N)
|
506 |
+
if factor > 1 and factor < N:
|
507 |
+
proper_factor.add(factor)
|
508 |
+
while(N_copy % factor == 0):
|
509 |
+
N_copy //= factor
|
510 |
+
if isprime(N_copy):
|
511 |
+
proper_factor.add(N_copy)
|
512 |
+
break
|
513 |
+
if(N_copy == 1):
|
514 |
+
break
|
515 |
+
return proper_factor
|
venv/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py
ADDED
@@ -0,0 +1,1573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from sympy.core.function import Function
|
4 |
+
from sympy.core.numbers import igcd, igcdex, mod_inverse
|
5 |
+
from sympy.core.power import isqrt
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.polys import Poly
|
8 |
+
from sympy.polys.domains import ZZ
|
9 |
+
from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence
|
10 |
+
from .primetest import isprime
|
11 |
+
from .factor_ import factorint, trailing, totient, multiplicity, perfect_power
|
12 |
+
from sympy.utilities.misc import as_int
|
13 |
+
from sympy.core.random import _randint, randint
|
14 |
+
|
15 |
+
from itertools import cycle, product
|
16 |
+
|
17 |
+
|
18 |
+
def n_order(a, n):
|
19 |
+
"""Returns the order of ``a`` modulo ``n``.
|
20 |
+
|
21 |
+
The order of ``a`` modulo ``n`` is the smallest integer
|
22 |
+
``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.
|
23 |
+
|
24 |
+
Parameters
|
25 |
+
==========
|
26 |
+
|
27 |
+
a : integer
|
28 |
+
n : integer, n > 1. a and n should be relatively prime
|
29 |
+
|
30 |
+
Examples
|
31 |
+
========
|
32 |
+
|
33 |
+
>>> from sympy.ntheory import n_order
|
34 |
+
>>> n_order(3, 7)
|
35 |
+
6
|
36 |
+
>>> n_order(4, 7)
|
37 |
+
3
|
38 |
+
"""
|
39 |
+
from collections import defaultdict
|
40 |
+
a, n = as_int(a), as_int(n)
|
41 |
+
if n <= 1:
|
42 |
+
raise ValueError("n should be an integer greater than 1")
|
43 |
+
a = a % n
|
44 |
+
# Trivial
|
45 |
+
if a == 1:
|
46 |
+
return 1
|
47 |
+
if igcd(a, n) != 1:
|
48 |
+
raise ValueError("The two numbers should be relatively prime")
|
49 |
+
# We want to calculate
|
50 |
+
# order = totient(n), factors = factorint(order)
|
51 |
+
factors = defaultdict(int)
|
52 |
+
for px, kx in factorint(n).items():
|
53 |
+
if kx > 1:
|
54 |
+
factors[px] += kx - 1
|
55 |
+
for py, ky in factorint(px - 1).items():
|
56 |
+
factors[py] += ky
|
57 |
+
order = 1
|
58 |
+
for px, kx in factors.items():
|
59 |
+
order *= px**kx
|
60 |
+
# Now the `order` is the order of the group.
|
61 |
+
# The order of `a` divides the order of the group.
|
62 |
+
for p, e in factors.items():
|
63 |
+
for _ in range(e):
|
64 |
+
if pow(a, order // p, n) == 1:
|
65 |
+
order //= p
|
66 |
+
else:
|
67 |
+
break
|
68 |
+
return order
|
69 |
+
|
70 |
+
|
71 |
+
def _primitive_root_prime_iter(p):
|
72 |
+
"""
|
73 |
+
Generates the primitive roots for a prime ``p``
|
74 |
+
|
75 |
+
Examples
|
76 |
+
========
|
77 |
+
|
78 |
+
>>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
|
79 |
+
>>> list(_primitive_root_prime_iter(19))
|
80 |
+
[2, 3, 10, 13, 14, 15]
|
81 |
+
|
82 |
+
References
|
83 |
+
==========
|
84 |
+
|
85 |
+
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
|
86 |
+
|
87 |
+
"""
|
88 |
+
# it is assumed that p is an int
|
89 |
+
v = [(p - 1) // i for i in factorint(p - 1).keys()]
|
90 |
+
a = 2
|
91 |
+
while a < p:
|
92 |
+
for pw in v:
|
93 |
+
# a TypeError below may indicate that p was not an int
|
94 |
+
if pow(a, pw, p) == 1:
|
95 |
+
break
|
96 |
+
else:
|
97 |
+
yield a
|
98 |
+
a += 1
|
99 |
+
|
100 |
+
|
101 |
+
def primitive_root(p):
|
102 |
+
"""
|
103 |
+
Returns the smallest primitive root or None.
|
104 |
+
|
105 |
+
Parameters
|
106 |
+
==========
|
107 |
+
|
108 |
+
p : positive integer
|
109 |
+
|
110 |
+
Examples
|
111 |
+
========
|
112 |
+
|
113 |
+
>>> from sympy.ntheory.residue_ntheory import primitive_root
|
114 |
+
>>> primitive_root(19)
|
115 |
+
2
|
116 |
+
|
117 |
+
References
|
118 |
+
==========
|
119 |
+
|
120 |
+
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
|
121 |
+
.. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
|
122 |
+
|
123 |
+
"""
|
124 |
+
p = as_int(p)
|
125 |
+
if p < 1:
|
126 |
+
raise ValueError('p is required to be positive')
|
127 |
+
if p <= 2:
|
128 |
+
return 1
|
129 |
+
f = factorint(p)
|
130 |
+
if len(f) > 2:
|
131 |
+
return None
|
132 |
+
if len(f) == 2:
|
133 |
+
if 2 not in f or f[2] > 1:
|
134 |
+
return None
|
135 |
+
|
136 |
+
# case p = 2*p1**k, p1 prime
|
137 |
+
for p1, e1 in f.items():
|
138 |
+
if p1 != 2:
|
139 |
+
break
|
140 |
+
i = 1
|
141 |
+
while i < p:
|
142 |
+
i += 2
|
143 |
+
if i % p1 == 0:
|
144 |
+
continue
|
145 |
+
if is_primitive_root(i, p):
|
146 |
+
return i
|
147 |
+
|
148 |
+
else:
|
149 |
+
if 2 in f:
|
150 |
+
if p == 4:
|
151 |
+
return 3
|
152 |
+
return None
|
153 |
+
p1, n = list(f.items())[0]
|
154 |
+
if n > 1:
|
155 |
+
# see Ref [2], page 81
|
156 |
+
g = primitive_root(p1)
|
157 |
+
if is_primitive_root(g, p1**2):
|
158 |
+
return g
|
159 |
+
else:
|
160 |
+
for i in range(2, g + p1 + 1):
|
161 |
+
if igcd(i, p) == 1 and is_primitive_root(i, p):
|
162 |
+
return i
|
163 |
+
|
164 |
+
return next(_primitive_root_prime_iter(p))
|
165 |
+
|
166 |
+
|
167 |
+
def is_primitive_root(a, p):
|
168 |
+
"""
|
169 |
+
Returns True if ``a`` is a primitive root of ``p``.
|
170 |
+
|
171 |
+
``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
|
172 |
+
totient(p) is the smallest positive number s.t.
|
173 |
+
|
174 |
+
a**totient(p) cong 1 mod(p)
|
175 |
+
|
176 |
+
Parameters
|
177 |
+
==========
|
178 |
+
|
179 |
+
a : integer
|
180 |
+
p : integer, p > 1. a and p should be relatively prime
|
181 |
+
|
182 |
+
Examples
|
183 |
+
========
|
184 |
+
|
185 |
+
>>> from sympy.ntheory import is_primitive_root, n_order, totient
|
186 |
+
>>> is_primitive_root(3, 10)
|
187 |
+
True
|
188 |
+
>>> is_primitive_root(9, 10)
|
189 |
+
False
|
190 |
+
>>> n_order(3, 10) == totient(10)
|
191 |
+
True
|
192 |
+
>>> n_order(9, 10) == totient(10)
|
193 |
+
False
|
194 |
+
|
195 |
+
"""
|
196 |
+
a, p = as_int(a), as_int(p)
|
197 |
+
if p <= 1:
|
198 |
+
raise ValueError("p should be an integer greater than 1")
|
199 |
+
a = a % p
|
200 |
+
if igcd(a, p) != 1:
|
201 |
+
raise ValueError("The two numbers should be relatively prime")
|
202 |
+
# Primitive root of p exist only for
|
203 |
+
# p = 2, 4, q**e, 2*q**e (q is odd prime)
|
204 |
+
if p <= 4:
|
205 |
+
# The primitive root is only p-1.
|
206 |
+
return a == p - 1
|
207 |
+
t = trailing(p)
|
208 |
+
if t > 1:
|
209 |
+
return False
|
210 |
+
q = p >> t
|
211 |
+
if isprime(q):
|
212 |
+
group_order = q - 1
|
213 |
+
factors = set(factorint(q - 1).keys())
|
214 |
+
else:
|
215 |
+
m = perfect_power(q)
|
216 |
+
if not m:
|
217 |
+
return False
|
218 |
+
q, e = m
|
219 |
+
if not isprime(q):
|
220 |
+
return False
|
221 |
+
group_order = q**(e - 1)*(q - 1)
|
222 |
+
factors = set(factorint(q - 1).keys())
|
223 |
+
factors.add(q)
|
224 |
+
return all(pow(a, group_order // prime, p) != 1 for prime in factors)
|
225 |
+
|
226 |
+
|
227 |
+
def _sqrt_mod_tonelli_shanks(a, p):
|
228 |
+
"""
|
229 |
+
Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
|
230 |
+
|
231 |
+
References
|
232 |
+
==========
|
233 |
+
|
234 |
+
.. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101
|
235 |
+
|
236 |
+
"""
|
237 |
+
s = trailing(p - 1)
|
238 |
+
t = p >> s
|
239 |
+
# find a non-quadratic residue
|
240 |
+
while 1:
|
241 |
+
d = randint(2, p - 1)
|
242 |
+
r = legendre_symbol(d, p)
|
243 |
+
if r == -1:
|
244 |
+
break
|
245 |
+
#assert legendre_symbol(d, p) == -1
|
246 |
+
A = pow(a, t, p)
|
247 |
+
D = pow(d, t, p)
|
248 |
+
m = 0
|
249 |
+
for i in range(s):
|
250 |
+
adm = A*pow(D, m, p) % p
|
251 |
+
adm = pow(adm, 2**(s - 1 - i), p)
|
252 |
+
if adm % p == p - 1:
|
253 |
+
m += 2**i
|
254 |
+
#assert A*pow(D, m, p) % p == 1
|
255 |
+
x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
|
256 |
+
return x
|
257 |
+
|
258 |
+
|
259 |
+
def sqrt_mod(a, p, all_roots=False):
|
260 |
+
"""
|
261 |
+
Find a root of ``x**2 = a mod p``.
|
262 |
+
|
263 |
+
Parameters
|
264 |
+
==========
|
265 |
+
|
266 |
+
a : integer
|
267 |
+
p : positive integer
|
268 |
+
all_roots : if True the list of roots is returned or None
|
269 |
+
|
270 |
+
Notes
|
271 |
+
=====
|
272 |
+
|
273 |
+
If there is no root it is returned None; else the returned root
|
274 |
+
is less or equal to ``p // 2``; in general is not the smallest one.
|
275 |
+
It is returned ``p // 2`` only if it is the only root.
|
276 |
+
|
277 |
+
Use ``all_roots`` only when it is expected that all the roots fit
|
278 |
+
in memory; otherwise use ``sqrt_mod_iter``.
|
279 |
+
|
280 |
+
Examples
|
281 |
+
========
|
282 |
+
|
283 |
+
>>> from sympy.ntheory import sqrt_mod
|
284 |
+
>>> sqrt_mod(11, 43)
|
285 |
+
21
|
286 |
+
>>> sqrt_mod(17, 32, True)
|
287 |
+
[7, 9, 23, 25]
|
288 |
+
"""
|
289 |
+
if all_roots:
|
290 |
+
return sorted(sqrt_mod_iter(a, p))
|
291 |
+
try:
|
292 |
+
p = abs(as_int(p))
|
293 |
+
it = sqrt_mod_iter(a, p)
|
294 |
+
r = next(it)
|
295 |
+
if r > p // 2:
|
296 |
+
return p - r
|
297 |
+
elif r < p // 2:
|
298 |
+
return r
|
299 |
+
else:
|
300 |
+
try:
|
301 |
+
r = next(it)
|
302 |
+
if r > p // 2:
|
303 |
+
return p - r
|
304 |
+
except StopIteration:
|
305 |
+
pass
|
306 |
+
return r
|
307 |
+
except StopIteration:
|
308 |
+
return None
|
309 |
+
|
310 |
+
|
311 |
+
def _product(*iters):
|
312 |
+
"""
|
313 |
+
Cartesian product generator
|
314 |
+
|
315 |
+
Notes
|
316 |
+
=====
|
317 |
+
|
318 |
+
Unlike itertools.product, it works also with iterables which do not fit
|
319 |
+
in memory. See https://bugs.python.org/issue10109
|
320 |
+
|
321 |
+
Author: Fernando Sumudu
|
322 |
+
with small changes
|
323 |
+
"""
|
324 |
+
inf_iters = tuple(cycle(enumerate(it)) for it in iters)
|
325 |
+
num_iters = len(inf_iters)
|
326 |
+
cur_val = [None]*num_iters
|
327 |
+
|
328 |
+
first_v = True
|
329 |
+
while True:
|
330 |
+
i, p = 0, num_iters
|
331 |
+
while p and not i:
|
332 |
+
p -= 1
|
333 |
+
i, cur_val[p] = next(inf_iters[p])
|
334 |
+
|
335 |
+
if not p and not i:
|
336 |
+
if first_v:
|
337 |
+
first_v = False
|
338 |
+
else:
|
339 |
+
break
|
340 |
+
|
341 |
+
yield cur_val
|
342 |
+
|
343 |
+
|
344 |
+
def sqrt_mod_iter(a, p, domain=int):
|
345 |
+
"""
|
346 |
+
Iterate over solutions to ``x**2 = a mod p``.
|
347 |
+
|
348 |
+
Parameters
|
349 |
+
==========
|
350 |
+
|
351 |
+
a : integer
|
352 |
+
p : positive integer
|
353 |
+
domain : integer domain, ``int``, ``ZZ`` or ``Integer``
|
354 |
+
|
355 |
+
Examples
|
356 |
+
========
|
357 |
+
|
358 |
+
>>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
|
359 |
+
>>> list(sqrt_mod_iter(11, 43))
|
360 |
+
[21, 22]
|
361 |
+
"""
|
362 |
+
a, p = as_int(a), abs(as_int(p))
|
363 |
+
if isprime(p):
|
364 |
+
a = a % p
|
365 |
+
if a == 0:
|
366 |
+
res = _sqrt_mod1(a, p, 1)
|
367 |
+
else:
|
368 |
+
res = _sqrt_mod_prime_power(a, p, 1)
|
369 |
+
if res:
|
370 |
+
if domain is ZZ:
|
371 |
+
yield from res
|
372 |
+
else:
|
373 |
+
for x in res:
|
374 |
+
yield domain(x)
|
375 |
+
else:
|
376 |
+
f = factorint(p)
|
377 |
+
v = []
|
378 |
+
pv = []
|
379 |
+
for px, ex in f.items():
|
380 |
+
if a % px == 0:
|
381 |
+
rx = _sqrt_mod1(a, px, ex)
|
382 |
+
if not rx:
|
383 |
+
return
|
384 |
+
else:
|
385 |
+
rx = _sqrt_mod_prime_power(a, px, ex)
|
386 |
+
if not rx:
|
387 |
+
return
|
388 |
+
v.append(rx)
|
389 |
+
pv.append(px**ex)
|
390 |
+
mm, e, s = gf_crt1(pv, ZZ)
|
391 |
+
if domain is ZZ:
|
392 |
+
for vx in _product(*v):
|
393 |
+
r = gf_crt2(vx, pv, mm, e, s, ZZ)
|
394 |
+
yield r
|
395 |
+
else:
|
396 |
+
for vx in _product(*v):
|
397 |
+
r = gf_crt2(vx, pv, mm, e, s, ZZ)
|
398 |
+
yield domain(r)
|
399 |
+
|
400 |
+
|
401 |
+
def _sqrt_mod_prime_power(a, p, k):
|
402 |
+
"""
|
403 |
+
Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``
|
404 |
+
|
405 |
+
Parameters
|
406 |
+
==========
|
407 |
+
|
408 |
+
a : integer
|
409 |
+
p : prime number
|
410 |
+
k : positive integer
|
411 |
+
|
412 |
+
Examples
|
413 |
+
========
|
414 |
+
|
415 |
+
>>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
|
416 |
+
>>> _sqrt_mod_prime_power(11, 43, 1)
|
417 |
+
[21, 22]
|
418 |
+
|
419 |
+
References
|
420 |
+
==========
|
421 |
+
|
422 |
+
.. [1] P. Hackman "Elementary Number Theory" (2009), page 160
|
423 |
+
.. [2] http://www.numbertheory.org/php/squareroot.html
|
424 |
+
.. [3] [Gathen99]_
|
425 |
+
"""
|
426 |
+
pk = p**k
|
427 |
+
a = a % pk
|
428 |
+
|
429 |
+
if k == 1:
|
430 |
+
if p == 2:
|
431 |
+
return [ZZ(a)]
|
432 |
+
if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1):
|
433 |
+
return None
|
434 |
+
|
435 |
+
if p % 4 == 3:
|
436 |
+
res = pow(a, (p + 1) // 4, p)
|
437 |
+
elif p % 8 == 5:
|
438 |
+
sign = pow(a, (p - 1) // 4, p)
|
439 |
+
if sign == 1:
|
440 |
+
res = pow(a, (p + 3) // 8, p)
|
441 |
+
else:
|
442 |
+
b = pow(4*a, (p - 5) // 8, p)
|
443 |
+
x = (2*a*b) % p
|
444 |
+
if pow(x, 2, p) == a:
|
445 |
+
res = x
|
446 |
+
else:
|
447 |
+
res = _sqrt_mod_tonelli_shanks(a, p)
|
448 |
+
|
449 |
+
# ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic;
|
450 |
+
# sort to get always the same result
|
451 |
+
return sorted([ZZ(res), ZZ(p - res)])
|
452 |
+
|
453 |
+
if k > 1:
|
454 |
+
# see Ref.[2]
|
455 |
+
if p == 2:
|
456 |
+
if a % 8 != 1:
|
457 |
+
return None
|
458 |
+
if k <= 3:
|
459 |
+
s = set()
|
460 |
+
for i in range(0, pk, 4):
|
461 |
+
s.add(1 + i)
|
462 |
+
s.add(-1 + i)
|
463 |
+
return list(s)
|
464 |
+
# according to Ref.[2] for k > 2 there are two solutions
|
465 |
+
# (mod 2**k-1), that is four solutions (mod 2**k), which can be
|
466 |
+
# obtained from the roots of x**2 = 0 (mod 8)
|
467 |
+
rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)]
|
468 |
+
# hensel lift them to solutions of x**2 = 0 (mod 2**k)
|
469 |
+
# if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
|
470 |
+
# then r + 2**(nx - 1) is a root mod 2**(nx+1)
|
471 |
+
n = 3
|
472 |
+
res = []
|
473 |
+
for r in rv:
|
474 |
+
nx = n
|
475 |
+
while nx < k:
|
476 |
+
r1 = (r**2 - a) >> nx
|
477 |
+
if r1 % 2:
|
478 |
+
r = r + (1 << (nx - 1))
|
479 |
+
#assert (r**2 - a)% (1 << (nx + 1)) == 0
|
480 |
+
nx += 1
|
481 |
+
if r not in res:
|
482 |
+
res.append(r)
|
483 |
+
x = r + (1 << (k - 1))
|
484 |
+
#assert (x**2 - a) % pk == 0
|
485 |
+
if x < (1 << nx) and x not in res:
|
486 |
+
if (x**2 - a) % pk == 0:
|
487 |
+
res.append(x)
|
488 |
+
return res
|
489 |
+
rv = _sqrt_mod_prime_power(a, p, 1)
|
490 |
+
if not rv:
|
491 |
+
return None
|
492 |
+
r = rv[0]
|
493 |
+
fr = r**2 - a
|
494 |
+
# hensel lifting with Newton iteration, see Ref.[3] chapter 9
|
495 |
+
# with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
|
496 |
+
n = 1
|
497 |
+
px = p
|
498 |
+
while 1:
|
499 |
+
n1 = n
|
500 |
+
n1 *= 2
|
501 |
+
if n1 > k:
|
502 |
+
break
|
503 |
+
n = n1
|
504 |
+
px = px**2
|
505 |
+
frinv = igcdex(2*r, px)[0]
|
506 |
+
r = (r - fr*frinv) % px
|
507 |
+
fr = r**2 - a
|
508 |
+
if n < k:
|
509 |
+
px = p**k
|
510 |
+
frinv = igcdex(2*r, px)[0]
|
511 |
+
r = (r - fr*frinv) % px
|
512 |
+
return [r, px - r]
|
513 |
+
|
514 |
+
|
515 |
+
def _sqrt_mod1(a, p, n):
|
516 |
+
"""
|
517 |
+
Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``
|
518 |
+
|
519 |
+
see http://www.numbertheory.org/php/squareroot.html
|
520 |
+
"""
|
521 |
+
pn = p**n
|
522 |
+
a = a % pn
|
523 |
+
if a == 0:
|
524 |
+
# case gcd(a, p**k) = p**n
|
525 |
+
m = n // 2
|
526 |
+
if n % 2 == 1:
|
527 |
+
pm1 = p**(m + 1)
|
528 |
+
def _iter0a():
|
529 |
+
i = 0
|
530 |
+
while i < pn:
|
531 |
+
yield i
|
532 |
+
i += pm1
|
533 |
+
return _iter0a()
|
534 |
+
else:
|
535 |
+
pm = p**m
|
536 |
+
def _iter0b():
|
537 |
+
i = 0
|
538 |
+
while i < pn:
|
539 |
+
yield i
|
540 |
+
i += pm
|
541 |
+
return _iter0b()
|
542 |
+
|
543 |
+
# case gcd(a, p**k) = p**r, r < n
|
544 |
+
f = factorint(a)
|
545 |
+
r = f[p]
|
546 |
+
if r % 2 == 1:
|
547 |
+
return None
|
548 |
+
m = r // 2
|
549 |
+
a1 = a >> r
|
550 |
+
if p == 2:
|
551 |
+
if n - r == 1:
|
552 |
+
pnm1 = 1 << (n - m + 1)
|
553 |
+
pm1 = 1 << (m + 1)
|
554 |
+
def _iter1():
|
555 |
+
k = 1 << (m + 2)
|
556 |
+
i = 1 << m
|
557 |
+
while i < pnm1:
|
558 |
+
j = i
|
559 |
+
while j < pn:
|
560 |
+
yield j
|
561 |
+
j += k
|
562 |
+
i += pm1
|
563 |
+
return _iter1()
|
564 |
+
if n - r == 2:
|
565 |
+
res = _sqrt_mod_prime_power(a1, p, n - r)
|
566 |
+
if res is None:
|
567 |
+
return None
|
568 |
+
pnm = 1 << (n - m)
|
569 |
+
def _iter2():
|
570 |
+
s = set()
|
571 |
+
for r in res:
|
572 |
+
i = 0
|
573 |
+
while i < pn:
|
574 |
+
x = (r << m) + i
|
575 |
+
if x not in s:
|
576 |
+
s.add(x)
|
577 |
+
yield x
|
578 |
+
i += pnm
|
579 |
+
return _iter2()
|
580 |
+
if n - r > 2:
|
581 |
+
res = _sqrt_mod_prime_power(a1, p, n - r)
|
582 |
+
if res is None:
|
583 |
+
return None
|
584 |
+
pnm1 = 1 << (n - m - 1)
|
585 |
+
def _iter3():
|
586 |
+
s = set()
|
587 |
+
for r in res:
|
588 |
+
i = 0
|
589 |
+
while i < pn:
|
590 |
+
x = ((r << m) + i) % pn
|
591 |
+
if x not in s:
|
592 |
+
s.add(x)
|
593 |
+
yield x
|
594 |
+
i += pnm1
|
595 |
+
return _iter3()
|
596 |
+
else:
|
597 |
+
m = r // 2
|
598 |
+
a1 = a // p**r
|
599 |
+
res1 = _sqrt_mod_prime_power(a1, p, n - r)
|
600 |
+
if res1 is None:
|
601 |
+
return None
|
602 |
+
pm = p**m
|
603 |
+
pnr = p**(n-r)
|
604 |
+
pnm = p**(n-m)
|
605 |
+
|
606 |
+
def _iter4():
|
607 |
+
s = set()
|
608 |
+
pm = p**m
|
609 |
+
for rx in res1:
|
610 |
+
i = 0
|
611 |
+
while i < pnm:
|
612 |
+
x = ((rx + i) % pn)
|
613 |
+
if x not in s:
|
614 |
+
s.add(x)
|
615 |
+
yield x*pm
|
616 |
+
i += pnr
|
617 |
+
return _iter4()
|
618 |
+
|
619 |
+
|
620 |
+
def is_quad_residue(a, p):
|
621 |
+
"""
|
622 |
+
Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
|
623 |
+
i.e a % p in set([i**2 % p for i in range(p)]).
|
624 |
+
|
625 |
+
Examples
|
626 |
+
========
|
627 |
+
|
628 |
+
If ``p`` is an odd
|
629 |
+
prime, an iterative method is used to make the determination:
|
630 |
+
|
631 |
+
>>> from sympy.ntheory import is_quad_residue
|
632 |
+
>>> sorted(set([i**2 % 7 for i in range(7)]))
|
633 |
+
[0, 1, 2, 4]
|
634 |
+
>>> [j for j in range(7) if is_quad_residue(j, 7)]
|
635 |
+
[0, 1, 2, 4]
|
636 |
+
|
637 |
+
See Also
|
638 |
+
========
|
639 |
+
|
640 |
+
legendre_symbol, jacobi_symbol
|
641 |
+
"""
|
642 |
+
a, p = as_int(a), as_int(p)
|
643 |
+
if p < 1:
|
644 |
+
raise ValueError('p must be > 0')
|
645 |
+
if a >= p or a < 0:
|
646 |
+
a = a % p
|
647 |
+
if a < 2 or p < 3:
|
648 |
+
return True
|
649 |
+
if not isprime(p):
|
650 |
+
if p % 2 and jacobi_symbol(a, p) == -1:
|
651 |
+
return False
|
652 |
+
r = sqrt_mod(a, p)
|
653 |
+
if r is None:
|
654 |
+
return False
|
655 |
+
else:
|
656 |
+
return True
|
657 |
+
|
658 |
+
return pow(a, (p - 1) // 2, p) == 1
|
659 |
+
|
660 |
+
|
661 |
+
def is_nthpow_residue(a, n, m):
|
662 |
+
"""
|
663 |
+
Returns True if ``x**n == a (mod m)`` has solutions.
|
664 |
+
|
665 |
+
References
|
666 |
+
==========
|
667 |
+
|
668 |
+
.. [1] P. Hackman "Elementary Number Theory" (2009), page 76
|
669 |
+
|
670 |
+
"""
|
671 |
+
a = a % m
|
672 |
+
a, n, m = as_int(a), as_int(n), as_int(m)
|
673 |
+
if m <= 0:
|
674 |
+
raise ValueError('m must be > 0')
|
675 |
+
if n < 0:
|
676 |
+
raise ValueError('n must be >= 0')
|
677 |
+
if n == 0:
|
678 |
+
if m == 1:
|
679 |
+
return False
|
680 |
+
return a == 1
|
681 |
+
if a == 0:
|
682 |
+
return True
|
683 |
+
if n == 1:
|
684 |
+
return True
|
685 |
+
if n == 2:
|
686 |
+
return is_quad_residue(a, m)
|
687 |
+
return _is_nthpow_residue_bign(a, n, m)
|
688 |
+
|
689 |
+
|
690 |
+
def _is_nthpow_residue_bign(a, n, m):
|
691 |
+
r"""Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`."""
|
692 |
+
# assert n > 2
|
693 |
+
# assert a > 0 and m > 0
|
694 |
+
if primitive_root(m) is None or igcd(a, m) != 1:
|
695 |
+
# assert m >= 8
|
696 |
+
for prime, power in factorint(m).items():
|
697 |
+
if not _is_nthpow_residue_bign_prime_power(a, n, prime, power):
|
698 |
+
return False
|
699 |
+
return True
|
700 |
+
f = totient(m)
|
701 |
+
k = int(f // igcd(f, n))
|
702 |
+
return pow(a, k, int(m)) == 1
|
703 |
+
|
704 |
+
|
705 |
+
def _is_nthpow_residue_bign_prime_power(a, n, p, k):
|
706 |
+
r"""Returns True/False if a solution for `x^n = a \pmod{p^k}`
|
707 |
+
does/does not exist."""
|
708 |
+
# assert a > 0
|
709 |
+
# assert n > 2
|
710 |
+
# assert p is prime
|
711 |
+
# assert k > 0
|
712 |
+
if a % p:
|
713 |
+
if p != 2:
|
714 |
+
return _is_nthpow_residue_bign(a, n, pow(p, k))
|
715 |
+
if n & 1:
|
716 |
+
return True
|
717 |
+
c = trailing(n)
|
718 |
+
return a % pow(2, min(c + 2, k)) == 1
|
719 |
+
else:
|
720 |
+
a %= pow(p, k)
|
721 |
+
if not a:
|
722 |
+
return True
|
723 |
+
mu = multiplicity(p, a)
|
724 |
+
if mu % n:
|
725 |
+
return False
|
726 |
+
pm = pow(p, mu)
|
727 |
+
return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu)
|
728 |
+
|
729 |
+
|
730 |
+
def _nthroot_mod2(s, q, p):
|
731 |
+
f = factorint(q)
|
732 |
+
v = []
|
733 |
+
for b, e in f.items():
|
734 |
+
v.extend([b]*e)
|
735 |
+
for qx in v:
|
736 |
+
s = _nthroot_mod1(s, qx, p, False)
|
737 |
+
return s
|
738 |
+
|
739 |
+
|
740 |
+
def _nthroot_mod1(s, q, p, all_roots):
|
741 |
+
"""
|
742 |
+
Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``
|
743 |
+
|
744 |
+
References
|
745 |
+
==========
|
746 |
+
|
747 |
+
.. [1] A. M. Johnston "A Generalized qth Root Algorithm"
|
748 |
+
|
749 |
+
"""
|
750 |
+
g = primitive_root(p)
|
751 |
+
if not isprime(q):
|
752 |
+
r = _nthroot_mod2(s, q, p)
|
753 |
+
else:
|
754 |
+
f = p - 1
|
755 |
+
assert (p - 1) % q == 0
|
756 |
+
# determine k
|
757 |
+
k = 0
|
758 |
+
while f % q == 0:
|
759 |
+
k += 1
|
760 |
+
f = f // q
|
761 |
+
# find z, x, r1
|
762 |
+
f1 = igcdex(-f, q)[0] % q
|
763 |
+
z = f*f1
|
764 |
+
x = (1 + z) // q
|
765 |
+
r1 = pow(s, x, p)
|
766 |
+
s1 = pow(s, f, p)
|
767 |
+
h = pow(g, f*q, p)
|
768 |
+
t = discrete_log(p, s1, h)
|
769 |
+
g2 = pow(g, z*t, p)
|
770 |
+
g3 = igcdex(g2, p)[0]
|
771 |
+
r = r1*g3 % p
|
772 |
+
#assert pow(r, q, p) == s
|
773 |
+
res = [r]
|
774 |
+
h = pow(g, (p - 1) // q, p)
|
775 |
+
#assert pow(h, q, p) == 1
|
776 |
+
hx = r
|
777 |
+
for i in range(q - 1):
|
778 |
+
hx = (hx*h) % p
|
779 |
+
res.append(hx)
|
780 |
+
if all_roots:
|
781 |
+
res.sort()
|
782 |
+
return res
|
783 |
+
return min(res)
|
784 |
+
|
785 |
+
|
786 |
+
|
787 |
+
def _help(m, prime_modulo_method, diff_method, expr_val):
|
788 |
+
"""
|
789 |
+
Helper function for _nthroot_mod_composite and polynomial_congruence.
|
790 |
+
|
791 |
+
Parameters
|
792 |
+
==========
|
793 |
+
|
794 |
+
m : positive integer
|
795 |
+
prime_modulo_method : function to calculate the root of the congruence
|
796 |
+
equation for the prime divisors of m
|
797 |
+
diff_method : function to calculate derivative of expression at any
|
798 |
+
given point
|
799 |
+
expr_val : function to calculate value of the expression at any
|
800 |
+
given point
|
801 |
+
"""
|
802 |
+
from sympy.ntheory.modular import crt
|
803 |
+
f = factorint(m)
|
804 |
+
dd = {}
|
805 |
+
for p, e in f.items():
|
806 |
+
tot_roots = set()
|
807 |
+
if e == 1:
|
808 |
+
tot_roots.update(prime_modulo_method(p))
|
809 |
+
else:
|
810 |
+
for root in prime_modulo_method(p):
|
811 |
+
diff = diff_method(root, p)
|
812 |
+
if diff != 0:
|
813 |
+
ppow = p
|
814 |
+
m_inv = mod_inverse(diff, p)
|
815 |
+
for j in range(1, e):
|
816 |
+
ppow *= p
|
817 |
+
root = (root - expr_val(root, ppow) * m_inv) % ppow
|
818 |
+
tot_roots.add(root)
|
819 |
+
else:
|
820 |
+
new_base = p
|
821 |
+
roots_in_base = {root}
|
822 |
+
while new_base < pow(p, e):
|
823 |
+
new_base *= p
|
824 |
+
new_roots = set()
|
825 |
+
for k in roots_in_base:
|
826 |
+
if expr_val(k, new_base)!= 0:
|
827 |
+
continue
|
828 |
+
while k not in new_roots:
|
829 |
+
new_roots.add(k)
|
830 |
+
k = (k + (new_base // p)) % new_base
|
831 |
+
roots_in_base = new_roots
|
832 |
+
tot_roots = tot_roots | roots_in_base
|
833 |
+
if tot_roots == set():
|
834 |
+
return []
|
835 |
+
dd[pow(p, e)] = tot_roots
|
836 |
+
a = []
|
837 |
+
m = []
|
838 |
+
for x, y in dd.items():
|
839 |
+
m.append(x)
|
840 |
+
a.append(list(y))
|
841 |
+
return sorted({crt(m, list(i))[0] for i in product(*a)})
|
842 |
+
|
843 |
+
|
844 |
+
def _nthroot_mod_composite(a, n, m):
|
845 |
+
"""
|
846 |
+
Find the solutions to ``x**n = a mod m`` when m is not prime.
|
847 |
+
"""
|
848 |
+
return _help(m,
|
849 |
+
lambda p: nthroot_mod(a, n, p, True),
|
850 |
+
lambda root, p: (pow(root, n - 1, p) * (n % p)) % p,
|
851 |
+
lambda root, p: (pow(root, n, p) - a) % p)
|
852 |
+
|
853 |
+
|
854 |
+
def nthroot_mod(a, n, p, all_roots=False):
|
855 |
+
"""
|
856 |
+
Find the solutions to ``x**n = a mod p``.
|
857 |
+
|
858 |
+
Parameters
|
859 |
+
==========
|
860 |
+
|
861 |
+
a : integer
|
862 |
+
n : positive integer
|
863 |
+
p : positive integer
|
864 |
+
all_roots : if False returns the smallest root, else the list of roots
|
865 |
+
|
866 |
+
Examples
|
867 |
+
========
|
868 |
+
|
869 |
+
>>> from sympy.ntheory.residue_ntheory import nthroot_mod
|
870 |
+
>>> nthroot_mod(11, 4, 19)
|
871 |
+
8
|
872 |
+
>>> nthroot_mod(11, 4, 19, True)
|
873 |
+
[8, 11]
|
874 |
+
>>> nthroot_mod(68, 3, 109)
|
875 |
+
23
|
876 |
+
"""
|
877 |
+
a = a % p
|
878 |
+
a, n, p = as_int(a), as_int(n), as_int(p)
|
879 |
+
|
880 |
+
if n == 2:
|
881 |
+
return sqrt_mod(a, p, all_roots)
|
882 |
+
# see Hackman "Elementary Number Theory" (2009), page 76
|
883 |
+
if not isprime(p):
|
884 |
+
return _nthroot_mod_composite(a, n, p)
|
885 |
+
if a % p == 0:
|
886 |
+
return [0]
|
887 |
+
if not is_nthpow_residue(a, n, p):
|
888 |
+
return [] if all_roots else None
|
889 |
+
if (p - 1) % n == 0:
|
890 |
+
return _nthroot_mod1(a, n, p, all_roots)
|
891 |
+
# The roots of ``x**n - a = 0 (mod p)`` are roots of
|
892 |
+
# ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
|
893 |
+
pa = n
|
894 |
+
pb = p - 1
|
895 |
+
b = 1
|
896 |
+
if pa < pb:
|
897 |
+
a, pa, b, pb = b, pb, a, pa
|
898 |
+
while pb:
|
899 |
+
# x**pa - a = 0; x**pb - b = 0
|
900 |
+
# x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a =
|
901 |
+
# b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p
|
902 |
+
q, r = divmod(pa, pb)
|
903 |
+
c = pow(b, q, p)
|
904 |
+
c = igcdex(c, p)[0]
|
905 |
+
c = (c * a) % p
|
906 |
+
pa, pb = pb, r
|
907 |
+
a, b = b, c
|
908 |
+
if pa == 1:
|
909 |
+
if all_roots:
|
910 |
+
res = [a]
|
911 |
+
else:
|
912 |
+
res = a
|
913 |
+
elif pa == 2:
|
914 |
+
return sqrt_mod(a, p, all_roots)
|
915 |
+
else:
|
916 |
+
res = _nthroot_mod1(a, pa, p, all_roots)
|
917 |
+
return res
|
918 |
+
|
919 |
+
|
920 |
+
def quadratic_residues(p) -> list[int]:
|
921 |
+
"""
|
922 |
+
Returns the list of quadratic residues.
|
923 |
+
|
924 |
+
Examples
|
925 |
+
========
|
926 |
+
|
927 |
+
>>> from sympy.ntheory.residue_ntheory import quadratic_residues
|
928 |
+
>>> quadratic_residues(7)
|
929 |
+
[0, 1, 2, 4]
|
930 |
+
"""
|
931 |
+
p = as_int(p)
|
932 |
+
r = {pow(i, 2, p) for i in range(p // 2 + 1)}
|
933 |
+
return sorted(r)
|
934 |
+
|
935 |
+
|
936 |
+
def legendre_symbol(a, p):
|
937 |
+
r"""
|
938 |
+
Returns the Legendre symbol `(a / p)`.
|
939 |
+
|
940 |
+
For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
|
941 |
+
defined as
|
942 |
+
|
943 |
+
.. math ::
|
944 |
+
\genfrac(){}{}{a}{p} = \begin{cases}
|
945 |
+
0 & \text{if } p \text{ divides } a\\
|
946 |
+
1 & \text{if } a \text{ is a quadratic residue modulo } p\\
|
947 |
+
-1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
|
948 |
+
\end{cases}
|
949 |
+
|
950 |
+
Parameters
|
951 |
+
==========
|
952 |
+
|
953 |
+
a : integer
|
954 |
+
p : odd prime
|
955 |
+
|
956 |
+
Examples
|
957 |
+
========
|
958 |
+
|
959 |
+
>>> from sympy.ntheory import legendre_symbol
|
960 |
+
>>> [legendre_symbol(i, 7) for i in range(7)]
|
961 |
+
[0, 1, 1, -1, 1, -1, -1]
|
962 |
+
>>> sorted(set([i**2 % 7 for i in range(7)]))
|
963 |
+
[0, 1, 2, 4]
|
964 |
+
|
965 |
+
See Also
|
966 |
+
========
|
967 |
+
|
968 |
+
is_quad_residue, jacobi_symbol
|
969 |
+
|
970 |
+
"""
|
971 |
+
a, p = as_int(a), as_int(p)
|
972 |
+
if not isprime(p) or p == 2:
|
973 |
+
raise ValueError("p should be an odd prime")
|
974 |
+
a = a % p
|
975 |
+
if not a:
|
976 |
+
return 0
|
977 |
+
if pow(a, (p - 1) // 2, p) == 1:
|
978 |
+
return 1
|
979 |
+
return -1
|
980 |
+
|
981 |
+
|
982 |
+
def jacobi_symbol(m, n):
|
983 |
+
r"""
|
984 |
+
Returns the Jacobi symbol `(m / n)`.
|
985 |
+
|
986 |
+
For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
|
987 |
+
is defined as the product of the Legendre symbols corresponding to the
|
988 |
+
prime factors of ``n``:
|
989 |
+
|
990 |
+
.. math ::
|
991 |
+
\genfrac(){}{}{m}{n} =
|
992 |
+
\genfrac(){}{}{m}{p^{1}}^{\alpha_1}
|
993 |
+
\genfrac(){}{}{m}{p^{2}}^{\alpha_2}
|
994 |
+
...
|
995 |
+
\genfrac(){}{}{m}{p^{k}}^{\alpha_k}
|
996 |
+
\text{ where } n =
|
997 |
+
p_1^{\alpha_1}
|
998 |
+
p_2^{\alpha_2}
|
999 |
+
...
|
1000 |
+
p_k^{\alpha_k}
|
1001 |
+
|
1002 |
+
Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
|
1003 |
+
then ``m`` is a quadratic nonresidue modulo ``n``.
|
1004 |
+
|
1005 |
+
But, unlike the Legendre symbol, if the Jacobi symbol
|
1006 |
+
`\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
|
1007 |
+
modulo ``n``.
|
1008 |
+
|
1009 |
+
Parameters
|
1010 |
+
==========
|
1011 |
+
|
1012 |
+
m : integer
|
1013 |
+
n : odd positive integer
|
1014 |
+
|
1015 |
+
Examples
|
1016 |
+
========
|
1017 |
+
|
1018 |
+
>>> from sympy.ntheory import jacobi_symbol, legendre_symbol
|
1019 |
+
>>> from sympy import S
|
1020 |
+
>>> jacobi_symbol(45, 77)
|
1021 |
+
-1
|
1022 |
+
>>> jacobi_symbol(60, 121)
|
1023 |
+
1
|
1024 |
+
|
1025 |
+
The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
|
1026 |
+
be demonstrated as follows:
|
1027 |
+
|
1028 |
+
>>> L = legendre_symbol
|
1029 |
+
>>> S(45).factors()
|
1030 |
+
{3: 2, 5: 1}
|
1031 |
+
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
|
1032 |
+
True
|
1033 |
+
|
1034 |
+
See Also
|
1035 |
+
========
|
1036 |
+
|
1037 |
+
is_quad_residue, legendre_symbol
|
1038 |
+
"""
|
1039 |
+
m, n = as_int(m), as_int(n)
|
1040 |
+
if n < 0 or not n % 2:
|
1041 |
+
raise ValueError("n should be an odd positive integer")
|
1042 |
+
if m < 0 or m > n:
|
1043 |
+
m %= n
|
1044 |
+
if not m:
|
1045 |
+
return int(n == 1)
|
1046 |
+
if n == 1 or m == 1:
|
1047 |
+
return 1
|
1048 |
+
if igcd(m, n) != 1:
|
1049 |
+
return 0
|
1050 |
+
|
1051 |
+
j = 1
|
1052 |
+
while m != 0:
|
1053 |
+
while m % 2 == 0 and m > 0:
|
1054 |
+
m >>= 1
|
1055 |
+
if n % 8 in [3, 5]:
|
1056 |
+
j = -j
|
1057 |
+
m, n = n, m
|
1058 |
+
if m % 4 == n % 4 == 3:
|
1059 |
+
j = -j
|
1060 |
+
m %= n
|
1061 |
+
return j
|
1062 |
+
|
1063 |
+
|
1064 |
+
class mobius(Function):
|
1065 |
+
"""
|
1066 |
+
Mobius function maps natural number to {-1, 0, 1}
|
1067 |
+
|
1068 |
+
It is defined as follows:
|
1069 |
+
1) `1` if `n = 1`.
|
1070 |
+
2) `0` if `n` has a squared prime factor.
|
1071 |
+
3) `(-1)^k` if `n` is a square-free positive integer with `k`
|
1072 |
+
number of prime factors.
|
1073 |
+
|
1074 |
+
It is an important multiplicative function in number theory
|
1075 |
+
and combinatorics. It has applications in mathematical series,
|
1076 |
+
algebraic number theory and also physics (Fermion operator has very
|
1077 |
+
concrete realization with Mobius Function model).
|
1078 |
+
|
1079 |
+
Parameters
|
1080 |
+
==========
|
1081 |
+
|
1082 |
+
n : positive integer
|
1083 |
+
|
1084 |
+
Examples
|
1085 |
+
========
|
1086 |
+
|
1087 |
+
>>> from sympy.ntheory import mobius
|
1088 |
+
>>> mobius(13*7)
|
1089 |
+
1
|
1090 |
+
>>> mobius(1)
|
1091 |
+
1
|
1092 |
+
>>> mobius(13*7*5)
|
1093 |
+
-1
|
1094 |
+
>>> mobius(13**2)
|
1095 |
+
0
|
1096 |
+
|
1097 |
+
References
|
1098 |
+
==========
|
1099 |
+
|
1100 |
+
.. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
|
1101 |
+
.. [2] Thomas Koshy "Elementary Number Theory with Applications"
|
1102 |
+
|
1103 |
+
"""
|
1104 |
+
@classmethod
|
1105 |
+
def eval(cls, n):
|
1106 |
+
if n.is_integer:
|
1107 |
+
if n.is_positive is not True:
|
1108 |
+
raise ValueError("n should be a positive integer")
|
1109 |
+
else:
|
1110 |
+
raise TypeError("n should be an integer")
|
1111 |
+
if n.is_prime:
|
1112 |
+
return S.NegativeOne
|
1113 |
+
elif n is S.One:
|
1114 |
+
return S.One
|
1115 |
+
elif n.is_Integer:
|
1116 |
+
a = factorint(n)
|
1117 |
+
if any(i > 1 for i in a.values()):
|
1118 |
+
return S.Zero
|
1119 |
+
return S.NegativeOne**len(a)
|
1120 |
+
|
1121 |
+
|
1122 |
+
def _discrete_log_trial_mul(n, a, b, order=None):
|
1123 |
+
"""
|
1124 |
+
Trial multiplication algorithm for computing the discrete logarithm of
|
1125 |
+
``a`` to the base ``b`` modulo ``n``.
|
1126 |
+
|
1127 |
+
The algorithm finds the discrete logarithm using exhaustive search. This
|
1128 |
+
naive method is used as fallback algorithm of ``discrete_log`` when the
|
1129 |
+
group order is very small.
|
1130 |
+
|
1131 |
+
Examples
|
1132 |
+
========
|
1133 |
+
|
1134 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
|
1135 |
+
>>> _discrete_log_trial_mul(41, 15, 7)
|
1136 |
+
3
|
1137 |
+
|
1138 |
+
See Also
|
1139 |
+
========
|
1140 |
+
|
1141 |
+
discrete_log
|
1142 |
+
|
1143 |
+
References
|
1144 |
+
==========
|
1145 |
+
|
1146 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
1147 |
+
Vanstone, S. A. (1997).
|
1148 |
+
"""
|
1149 |
+
a %= n
|
1150 |
+
b %= n
|
1151 |
+
if order is None:
|
1152 |
+
order = n
|
1153 |
+
x = 1
|
1154 |
+
for i in range(order):
|
1155 |
+
if x == a:
|
1156 |
+
return i
|
1157 |
+
x = x * b % n
|
1158 |
+
raise ValueError("Log does not exist")
|
1159 |
+
|
1160 |
+
|
1161 |
+
def _discrete_log_shanks_steps(n, a, b, order=None):
|
1162 |
+
"""
|
1163 |
+
Baby-step giant-step algorithm for computing the discrete logarithm of
|
1164 |
+
``a`` to the base ``b`` modulo ``n``.
|
1165 |
+
|
1166 |
+
The algorithm is a time-memory trade-off of the method of exhaustive
|
1167 |
+
search. It uses `O(sqrt(m))` memory, where `m` is the group order.
|
1168 |
+
|
1169 |
+
Examples
|
1170 |
+
========
|
1171 |
+
|
1172 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
|
1173 |
+
>>> _discrete_log_shanks_steps(41, 15, 7)
|
1174 |
+
3
|
1175 |
+
|
1176 |
+
See Also
|
1177 |
+
========
|
1178 |
+
|
1179 |
+
discrete_log
|
1180 |
+
|
1181 |
+
References
|
1182 |
+
==========
|
1183 |
+
|
1184 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
1185 |
+
Vanstone, S. A. (1997).
|
1186 |
+
"""
|
1187 |
+
a %= n
|
1188 |
+
b %= n
|
1189 |
+
if order is None:
|
1190 |
+
order = n_order(b, n)
|
1191 |
+
m = isqrt(order) + 1
|
1192 |
+
T = {}
|
1193 |
+
x = 1
|
1194 |
+
for i in range(m):
|
1195 |
+
T[x] = i
|
1196 |
+
x = x * b % n
|
1197 |
+
z = mod_inverse(b, n)
|
1198 |
+
z = pow(z, m, n)
|
1199 |
+
x = a
|
1200 |
+
for i in range(m):
|
1201 |
+
if x in T:
|
1202 |
+
return i * m + T[x]
|
1203 |
+
x = x * z % n
|
1204 |
+
raise ValueError("Log does not exist")
|
1205 |
+
|
1206 |
+
|
1207 |
+
def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
|
1208 |
+
"""
|
1209 |
+
Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
|
1210 |
+
the base ``b`` modulo ``n``.
|
1211 |
+
|
1212 |
+
It is a randomized algorithm with the same expected running time as
|
1213 |
+
``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
|
1214 |
+
|
1215 |
+
Examples
|
1216 |
+
========
|
1217 |
+
|
1218 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
|
1219 |
+
>>> _discrete_log_pollard_rho(227, 3**7, 3)
|
1220 |
+
7
|
1221 |
+
|
1222 |
+
See Also
|
1223 |
+
========
|
1224 |
+
|
1225 |
+
discrete_log
|
1226 |
+
|
1227 |
+
References
|
1228 |
+
==========
|
1229 |
+
|
1230 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
1231 |
+
Vanstone, S. A. (1997).
|
1232 |
+
"""
|
1233 |
+
a %= n
|
1234 |
+
b %= n
|
1235 |
+
|
1236 |
+
if order is None:
|
1237 |
+
order = n_order(b, n)
|
1238 |
+
randint = _randint(rseed)
|
1239 |
+
|
1240 |
+
for i in range(retries):
|
1241 |
+
aa = randint(1, order - 1)
|
1242 |
+
ba = randint(1, order - 1)
|
1243 |
+
xa = pow(b, aa, n) * pow(a, ba, n) % n
|
1244 |
+
|
1245 |
+
c = xa % 3
|
1246 |
+
if c == 0:
|
1247 |
+
xb = a * xa % n
|
1248 |
+
ab = aa
|
1249 |
+
bb = (ba + 1) % order
|
1250 |
+
elif c == 1:
|
1251 |
+
xb = xa * xa % n
|
1252 |
+
ab = (aa + aa) % order
|
1253 |
+
bb = (ba + ba) % order
|
1254 |
+
else:
|
1255 |
+
xb = b * xa % n
|
1256 |
+
ab = (aa + 1) % order
|
1257 |
+
bb = ba
|
1258 |
+
|
1259 |
+
for j in range(order):
|
1260 |
+
c = xa % 3
|
1261 |
+
if c == 0:
|
1262 |
+
xa = a * xa % n
|
1263 |
+
ba = (ba + 1) % order
|
1264 |
+
elif c == 1:
|
1265 |
+
xa = xa * xa % n
|
1266 |
+
aa = (aa + aa) % order
|
1267 |
+
ba = (ba + ba) % order
|
1268 |
+
else:
|
1269 |
+
xa = b * xa % n
|
1270 |
+
aa = (aa + 1) % order
|
1271 |
+
|
1272 |
+
c = xb % 3
|
1273 |
+
if c == 0:
|
1274 |
+
xb = a * xb % n
|
1275 |
+
bb = (bb + 1) % order
|
1276 |
+
elif c == 1:
|
1277 |
+
xb = xb * xb % n
|
1278 |
+
ab = (ab + ab) % order
|
1279 |
+
bb = (bb + bb) % order
|
1280 |
+
else:
|
1281 |
+
xb = b * xb % n
|
1282 |
+
ab = (ab + 1) % order
|
1283 |
+
|
1284 |
+
c = xb % 3
|
1285 |
+
if c == 0:
|
1286 |
+
xb = a * xb % n
|
1287 |
+
bb = (bb + 1) % order
|
1288 |
+
elif c == 1:
|
1289 |
+
xb = xb * xb % n
|
1290 |
+
ab = (ab + ab) % order
|
1291 |
+
bb = (bb + bb) % order
|
1292 |
+
else:
|
1293 |
+
xb = b * xb % n
|
1294 |
+
ab = (ab + 1) % order
|
1295 |
+
|
1296 |
+
if xa == xb:
|
1297 |
+
r = (ba - bb) % order
|
1298 |
+
try:
|
1299 |
+
e = mod_inverse(r, order) * (ab - aa) % order
|
1300 |
+
if (pow(b, e, n) - a) % n == 0:
|
1301 |
+
return e
|
1302 |
+
except ValueError:
|
1303 |
+
pass
|
1304 |
+
break
|
1305 |
+
raise ValueError("Pollard's Rho failed to find logarithm")
|
1306 |
+
|
1307 |
+
|
1308 |
+
def _discrete_log_pohlig_hellman(n, a, b, order=None):
|
1309 |
+
"""
|
1310 |
+
Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
|
1311 |
+
the base ``b`` modulo ``n``.
|
1312 |
+
|
1313 |
+
In order to compute the discrete logarithm, the algorithm takes advantage
|
1314 |
+
of the factorization of the group order. It is more efficient when the
|
1315 |
+
group order factors into many small primes.
|
1316 |
+
|
1317 |
+
Examples
|
1318 |
+
========
|
1319 |
+
|
1320 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
|
1321 |
+
>>> _discrete_log_pohlig_hellman(251, 210, 71)
|
1322 |
+
197
|
1323 |
+
|
1324 |
+
See Also
|
1325 |
+
========
|
1326 |
+
|
1327 |
+
discrete_log
|
1328 |
+
|
1329 |
+
References
|
1330 |
+
==========
|
1331 |
+
|
1332 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
1333 |
+
Vanstone, S. A. (1997).
|
1334 |
+
"""
|
1335 |
+
from .modular import crt
|
1336 |
+
a %= n
|
1337 |
+
b %= n
|
1338 |
+
|
1339 |
+
if order is None:
|
1340 |
+
order = n_order(b, n)
|
1341 |
+
|
1342 |
+
f = factorint(order)
|
1343 |
+
l = [0] * len(f)
|
1344 |
+
|
1345 |
+
for i, (pi, ri) in enumerate(f.items()):
|
1346 |
+
for j in range(ri):
|
1347 |
+
gj = pow(b, l[i], n)
|
1348 |
+
aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n)
|
1349 |
+
bj = pow(b, order // pi, n)
|
1350 |
+
cj = discrete_log(n, aj, bj, pi, True)
|
1351 |
+
l[i] += cj * pi**j
|
1352 |
+
|
1353 |
+
d, _ = crt([pi**ri for pi, ri in f.items()], l)
|
1354 |
+
return d
|
1355 |
+
|
1356 |
+
|
1357 |
+
def discrete_log(n, a, b, order=None, prime_order=None):
|
1358 |
+
"""
|
1359 |
+
Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
|
1360 |
+
|
1361 |
+
This is a recursive function to reduce the discrete logarithm problem in
|
1362 |
+
cyclic groups of composite order to the problem in cyclic groups of prime
|
1363 |
+
order.
|
1364 |
+
|
1365 |
+
It employs different algorithms depending on the problem (subgroup order
|
1366 |
+
size, prime order or not):
|
1367 |
+
|
1368 |
+
* Trial multiplication
|
1369 |
+
* Baby-step giant-step
|
1370 |
+
* Pollard's Rho
|
1371 |
+
* Pohlig-Hellman
|
1372 |
+
|
1373 |
+
Examples
|
1374 |
+
========
|
1375 |
+
|
1376 |
+
>>> from sympy.ntheory import discrete_log
|
1377 |
+
>>> discrete_log(41, 15, 7)
|
1378 |
+
3
|
1379 |
+
|
1380 |
+
References
|
1381 |
+
==========
|
1382 |
+
|
1383 |
+
.. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
|
1384 |
+
.. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
1385 |
+
Vanstone, S. A. (1997).
|
1386 |
+
|
1387 |
+
"""
|
1388 |
+
n, a, b = as_int(n), as_int(a), as_int(b)
|
1389 |
+
if order is None:
|
1390 |
+
order = n_order(b, n)
|
1391 |
+
|
1392 |
+
if prime_order is None:
|
1393 |
+
prime_order = isprime(order)
|
1394 |
+
|
1395 |
+
if order < 1000:
|
1396 |
+
return _discrete_log_trial_mul(n, a, b, order)
|
1397 |
+
elif prime_order:
|
1398 |
+
if order < 1000000000000:
|
1399 |
+
return _discrete_log_shanks_steps(n, a, b, order)
|
1400 |
+
return _discrete_log_pollard_rho(n, a, b, order)
|
1401 |
+
|
1402 |
+
return _discrete_log_pohlig_hellman(n, a, b, order)
|
1403 |
+
|
1404 |
+
|
1405 |
+
|
1406 |
+
def quadratic_congruence(a, b, c, p):
|
1407 |
+
"""
|
1408 |
+
Find the solutions to ``a x**2 + b x + c = 0 mod p.
|
1409 |
+
|
1410 |
+
Parameters
|
1411 |
+
==========
|
1412 |
+
|
1413 |
+
a : int
|
1414 |
+
b : int
|
1415 |
+
c : int
|
1416 |
+
p : int
|
1417 |
+
A positive integer.
|
1418 |
+
"""
|
1419 |
+
a = as_int(a)
|
1420 |
+
b = as_int(b)
|
1421 |
+
c = as_int(c)
|
1422 |
+
p = as_int(p)
|
1423 |
+
a = a % p
|
1424 |
+
b = b % p
|
1425 |
+
c = c % p
|
1426 |
+
|
1427 |
+
if a == 0:
|
1428 |
+
return linear_congruence(b, -c, p)
|
1429 |
+
if p == 2:
|
1430 |
+
roots = []
|
1431 |
+
if c % 2 == 0:
|
1432 |
+
roots.append(0)
|
1433 |
+
if (a + b + c) % 2 == 0:
|
1434 |
+
roots.append(1)
|
1435 |
+
return roots
|
1436 |
+
if isprime(p):
|
1437 |
+
inv_a = mod_inverse(a, p)
|
1438 |
+
b *= inv_a
|
1439 |
+
c *= inv_a
|
1440 |
+
if b % 2 == 1:
|
1441 |
+
b = b + p
|
1442 |
+
d = ((b * b) // 4 - c) % p
|
1443 |
+
y = sqrt_mod(d, p, all_roots=True)
|
1444 |
+
res = set()
|
1445 |
+
for i in y:
|
1446 |
+
res.add((i - b // 2) % p)
|
1447 |
+
return sorted(res)
|
1448 |
+
y = sqrt_mod(b * b - 4 * a * c, 4 * a * p, all_roots=True)
|
1449 |
+
res = set()
|
1450 |
+
for i in y:
|
1451 |
+
root = linear_congruence(2 * a, i - b, 4 * a * p)
|
1452 |
+
for j in root:
|
1453 |
+
res.add(j % p)
|
1454 |
+
return sorted(res)
|
1455 |
+
|
1456 |
+
|
1457 |
+
def _polynomial_congruence_prime(coefficients, p):
|
1458 |
+
"""A helper function used by polynomial_congruence.
|
1459 |
+
It returns the root of a polynomial modulo prime number
|
1460 |
+
by naive search from [0, p).
|
1461 |
+
|
1462 |
+
Parameters
|
1463 |
+
==========
|
1464 |
+
|
1465 |
+
coefficients : list of integers
|
1466 |
+
p : prime number
|
1467 |
+
"""
|
1468 |
+
|
1469 |
+
roots = []
|
1470 |
+
rank = len(coefficients)
|
1471 |
+
for i in range(0, p):
|
1472 |
+
f_val = 0
|
1473 |
+
for coeff in range(0,rank - 1):
|
1474 |
+
f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p
|
1475 |
+
f_val = f_val + coefficients[-1]
|
1476 |
+
if f_val % p == 0:
|
1477 |
+
roots.append(i)
|
1478 |
+
return roots
|
1479 |
+
|
1480 |
+
|
1481 |
+
def _diff_poly(root, coefficients, p):
|
1482 |
+
"""A helper function used by polynomial_congruence.
|
1483 |
+
It returns the derivative of the polynomial evaluated at the
|
1484 |
+
root (mod p).
|
1485 |
+
|
1486 |
+
Parameters
|
1487 |
+
==========
|
1488 |
+
|
1489 |
+
coefficients : list of integers
|
1490 |
+
p : prime number
|
1491 |
+
root : integer
|
1492 |
+
"""
|
1493 |
+
|
1494 |
+
diff = 0
|
1495 |
+
rank = len(coefficients)
|
1496 |
+
for coeff in range(0, rank - 1):
|
1497 |
+
if not coefficients[coeff]:
|
1498 |
+
continue
|
1499 |
+
diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)*
|
1500 |
+
coefficients[coeff]) % p
|
1501 |
+
return diff % p
|
1502 |
+
|
1503 |
+
|
1504 |
+
def _val_poly(root, coefficients, p):
|
1505 |
+
"""A helper function used by polynomial_congruence.
|
1506 |
+
It returns value of the polynomial at root (mod p).
|
1507 |
+
|
1508 |
+
Parameters
|
1509 |
+
==========
|
1510 |
+
|
1511 |
+
coefficients : list of integers
|
1512 |
+
p : prime number
|
1513 |
+
root : integer
|
1514 |
+
"""
|
1515 |
+
rank = len(coefficients)
|
1516 |
+
f_val = 0
|
1517 |
+
for coeff in range(0, rank - 1):
|
1518 |
+
f_val = (f_val + pow(root, rank - coeff - 1, p)*
|
1519 |
+
coefficients[coeff]) % p
|
1520 |
+
f_val = f_val + coefficients[-1]
|
1521 |
+
return f_val % p
|
1522 |
+
|
1523 |
+
|
1524 |
+
def _valid_expr(expr):
|
1525 |
+
"""
|
1526 |
+
return coefficients of expr if it is a univariate polynomial
|
1527 |
+
with integer coefficients else raise a ValueError.
|
1528 |
+
"""
|
1529 |
+
|
1530 |
+
if not expr.is_polynomial():
|
1531 |
+
raise ValueError("The expression should be a polynomial")
|
1532 |
+
polynomial = Poly(expr)
|
1533 |
+
if not polynomial.is_univariate:
|
1534 |
+
raise ValueError("The expression should be univariate")
|
1535 |
+
if not polynomial.domain == ZZ:
|
1536 |
+
raise ValueError("The expression should should have integer coefficients")
|
1537 |
+
return polynomial.all_coeffs()
|
1538 |
+
|
1539 |
+
|
1540 |
+
def polynomial_congruence(expr, m):
|
1541 |
+
"""
|
1542 |
+
Find the solutions to a polynomial congruence equation modulo m.
|
1543 |
+
|
1544 |
+
Parameters
|
1545 |
+
==========
|
1546 |
+
|
1547 |
+
coefficients : Coefficients of the Polynomial
|
1548 |
+
m : positive integer
|
1549 |
+
|
1550 |
+
Examples
|
1551 |
+
========
|
1552 |
+
|
1553 |
+
>>> from sympy.ntheory import polynomial_congruence
|
1554 |
+
>>> from sympy.abc import x
|
1555 |
+
>>> expr = x**6 - 2*x**5 -35
|
1556 |
+
>>> polynomial_congruence(expr, 6125)
|
1557 |
+
[3257]
|
1558 |
+
"""
|
1559 |
+
coefficients = _valid_expr(expr)
|
1560 |
+
coefficients = [num % m for num in coefficients]
|
1561 |
+
rank = len(coefficients)
|
1562 |
+
if rank == 3:
|
1563 |
+
return quadratic_congruence(*coefficients, m)
|
1564 |
+
if rank == 2:
|
1565 |
+
return quadratic_congruence(0, *coefficients, m)
|
1566 |
+
if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients):
|
1567 |
+
return nthroot_mod(-coefficients[-1], rank - 1, m, True)
|
1568 |
+
if isprime(m):
|
1569 |
+
return _polynomial_congruence_prime(coefficients, m)
|
1570 |
+
return _help(m,
|
1571 |
+
lambda p: _polynomial_congruence_prime(coefficients, p),
|
1572 |
+
lambda root, p: _diff_poly(root, coefficients, p),
|
1573 |
+
lambda root, p: _val_poly(root, coefficients, p))
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (187 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc
ADDED
Binary file (9.52 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc
ADDED
Binary file (3.91 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc
ADDED
Binary file (2.29 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc
ADDED
Binary file (2.75 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc
ADDED
Binary file (26.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc
ADDED
Binary file (2.69 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc
ADDED
Binary file (4.85 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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(3.14))
|
127 |
+
|
128 |
+
# this will pick a random segment to compute every time
|
129 |
+
# it is run. If it ever fails, there is an error in the
|
130 |
+
# computation.
|
131 |
+
n = randint(0, len(dig))
|
132 |
+
prec = randint(0, len(dig) - n)
|
133 |
+
assert pi_hex_digits(n, prec) == dig[n: n + prec]
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import GoldenRatio as phi
|
2 |
+
from sympy.core.numbers import (Rational, pi)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.ntheory.continued_fraction import \
|
6 |
+
(continued_fraction_periodic as cf_p,
|
7 |
+
continued_fraction_iterator as cf_i,
|
8 |
+
continued_fraction_convergents as cf_c,
|
9 |
+
continued_fraction_reduce as cf_r,
|
10 |
+
continued_fraction as cf)
|
11 |
+
from sympy.testing.pytest import raises
|
12 |
+
|
13 |
+
|
14 |
+
def test_continued_fraction():
|
15 |
+
assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1)
|
16 |
+
assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1)
|
17 |
+
t = sqrt(2)
|
18 |
+
assert cf((1 + t)*(1 - t)) == cf(-1)
|
19 |
+
for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5,
|
20 |
+
(2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]:
|
21 |
+
assert (cf_r(cf(n)) - n).expand() == 0
|
22 |
+
assert (cf_r(cf(-n)) + n).expand() == 0
|
23 |
+
raises(ValueError, lambda: cf(sqrt(2 + sqrt(3))))
|
24 |
+
raises(ValueError, lambda: cf(sqrt(2) + sqrt(3)))
|
25 |
+
raises(ValueError, lambda: cf(pi))
|
26 |
+
raises(ValueError, lambda: cf(.1))
|
27 |
+
|
28 |
+
raises(ValueError, lambda: cf_p(1, 0, 0))
|
29 |
+
raises(ValueError, lambda: cf_p(1, 1, -1))
|
30 |
+
assert cf_p(4, 3, 0) == [1, 3]
|
31 |
+
assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
|
32 |
+
assert cf_p(1, 1, 0) == [1]
|
33 |
+
assert cf_p(3, 4, 0) == [0, 1, 3]
|
34 |
+
assert cf_p(4, 5, 0) == [0, 1, 4]
|
35 |
+
assert cf_p(5, 6, 0) == [0, 1, 5]
|
36 |
+
assert cf_p(11, 13, 0) == [0, 1, 5, 2]
|
37 |
+
assert cf_p(16, 19, 0) == [0, 1, 5, 3]
|
38 |
+
assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
|
39 |
+
assert cf_p(1, 2, 5) == [[1]]
|
40 |
+
assert cf_p(0, 1, 2) == [1, [2]]
|
41 |
+
assert cf_p(6, 7, 49) == [1, 1, 6]
|
42 |
+
assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
|
43 |
+
assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
|
44 |
+
assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
|
45 |
+
assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
|
46 |
+
|
47 |
+
def take(iterator, n=7):
|
48 |
+
res = []
|
49 |
+
for i, t in enumerate(cf_i(iterator)):
|
50 |
+
if i >= n:
|
51 |
+
break
|
52 |
+
res.append(t)
|
53 |
+
return res
|
54 |
+
|
55 |
+
assert take(phi) == [1, 1, 1, 1, 1, 1, 1]
|
56 |
+
assert take(pi) == [3, 7, 15, 1, 292, 1, 1]
|
57 |
+
|
58 |
+
assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2]
|
59 |
+
assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2]
|
60 |
+
|
61 |
+
assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)]
|
62 |
+
assert list(cf_c([2])) == [S(2)]
|
63 |
+
assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3),
|
64 |
+
Rational(8, 5), Rational(13, 8), Rational(21, 13)]
|
65 |
+
assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)]
|
66 |
+
|
67 |
+
assert cf_r([1, 6, 1, 8]) == Rational(71, 62)
|
68 |
+
assert cf_r([3]) == S(3)
|
69 |
+
assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29)
|
70 |
+
assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
|
71 |
+
assert cf_r([1, 5, 9]) == Rational(55, 46)
|
72 |
+
assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
|
73 |
+
assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2)
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.ntheory import count_digits, digits, is_palindromic
|
2 |
+
|
3 |
+
from sympy.testing.pytest import raises
|
4 |
+
|
5 |
+
|
6 |
+
def test_digits():
|
7 |
+
assert all([digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
|
8 |
+
for n in range(20)])
|
9 |
+
assert all([digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
|
10 |
+
for n in range(20)])
|
11 |
+
assert all([digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
|
12 |
+
for n in range(20)])
|
13 |
+
assert digits(2345, 34) == [34, 2, 0, 33]
|
14 |
+
assert digits(384753, 71) == [71, 1, 5, 23, 4]
|
15 |
+
assert digits(93409, 10) == [10, 9, 3, 4, 0, 9]
|
16 |
+
assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
|
17 |
+
assert digits(35, 10) == [10, 3, 5]
|
18 |
+
assert digits(35, 10, 3) == [10, 0, 3, 5]
|
19 |
+
assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5]
|
20 |
+
raises(ValueError, lambda: digits(2, 2, 1))
|
21 |
+
|
22 |
+
|
23 |
+
def test_count_digits():
|
24 |
+
assert count_digits(55, 2) == {1: 5, 0: 1}
|
25 |
+
assert count_digits(55, 10) == {5: 2}
|
26 |
+
n = count_digits(123)
|
27 |
+
assert n[4] == 0 and type(n[4]) is int
|
28 |
+
|
29 |
+
|
30 |
+
def test_is_palindromic():
|
31 |
+
assert is_palindromic(-11)
|
32 |
+
assert is_palindromic(11)
|
33 |
+
assert is_palindromic(0o121, 8)
|
34 |
+
assert not is_palindromic(123)
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.ntheory.ecm import ecm, Point
|
2 |
+
from sympy.testing.pytest import slow
|
3 |
+
|
4 |
+
@slow
|
5 |
+
def test_ecm():
|
6 |
+
assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297}
|
7 |
+
assert ecm(46167045131415113) == {43, 2634823, 407485517}
|
8 |
+
assert ecm(631211032315670776841) == {9312934919, 67777885039}
|
9 |
+
assert ecm(398883434337287) == {99476569, 4009823}
|
10 |
+
assert ecm(64211816600515193) == {281719, 359641, 633767}
|
11 |
+
assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123}
|
12 |
+
assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571}
|
13 |
+
assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803}
|
14 |
+
assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721}
|
15 |
+
#This takes ~10secs while factorint is not able to factorize this even in ~10mins
|
16 |
+
assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809}
|
17 |
+
|
18 |
+
|
19 |
+
def test_Point():
|
20 |
+
from sympy.core.numbers import mod_inverse
|
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)*mod_inverse(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.10/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.10/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.10/site-packages/sympy/ntheory/tests/test_factor_.py
ADDED
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import summation
|
2 |
+
from sympy.core.containers import Dict
|
3 |
+
from sympy.core.mul import Mul
|
4 |
+
from sympy.core.power import Pow
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import Symbol
|
7 |
+
from sympy.functions.combinatorial.factorials import factorial as fac
|
8 |
+
from sympy.core.evalf import bitcount
|
9 |
+
from sympy.core.numbers import Integer, Rational
|
10 |
+
|
11 |
+
from sympy.ntheory import (totient,
|
12 |
+
factorint, primefactors, divisors, nextprime,
|
13 |
+
primerange, pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial,
|
14 |
+
trailing, divisor_count, primorial, pollard_pm1, divisor_sigma,
|
15 |
+
factorrat, reduced_totient)
|
16 |
+
from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors,
|
17 |
+
antidivisors, antidivisor_count, core, udivisors, udivisor_sigma,
|
18 |
+
udivisor_count, proper_divisor_count, primenu, primeomega, small_trailing,
|
19 |
+
mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
|
20 |
+
is_deficient, is_amicable, dra, drm)
|
21 |
+
|
22 |
+
from sympy.testing.pytest import raises, slow
|
23 |
+
|
24 |
+
from sympy.utilities.iterables import capture
|
25 |
+
|
26 |
+
|
27 |
+
def fac_multiplicity(n, p):
|
28 |
+
"""Return the power of the prime number p in the
|
29 |
+
factorization of n!"""
|
30 |
+
if p > n:
|
31 |
+
return 0
|
32 |
+
if p > n//2:
|
33 |
+
return 1
|
34 |
+
q, m = n, 0
|
35 |
+
while q >= p:
|
36 |
+
q //= p
|
37 |
+
m += q
|
38 |
+
return m
|
39 |
+
|
40 |
+
|
41 |
+
def multiproduct(seq=(), start=1):
|
42 |
+
"""
|
43 |
+
Return the product of a sequence of factors with multiplicities,
|
44 |
+
times the value of the parameter ``start``. The input may be a
|
45 |
+
sequence of (factor, exponent) pairs or a dict of such pairs.
|
46 |
+
|
47 |
+
>>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
|
48 |
+
279936
|
49 |
+
|
50 |
+
"""
|
51 |
+
if not seq:
|
52 |
+
return start
|
53 |
+
if isinstance(seq, dict):
|
54 |
+
seq = iter(seq.items())
|
55 |
+
units = start
|
56 |
+
multi = []
|
57 |
+
for base, exp in seq:
|
58 |
+
if not exp:
|
59 |
+
continue
|
60 |
+
elif exp == 1:
|
61 |
+
units *= base
|
62 |
+
else:
|
63 |
+
if exp % 2:
|
64 |
+
units *= base
|
65 |
+
multi.append((base, exp//2))
|
66 |
+
return units * multiproduct(multi)**2
|
67 |
+
|
68 |
+
|
69 |
+
def test_trailing_bitcount():
|
70 |
+
assert trailing(0) == 0
|
71 |
+
assert trailing(1) == 0
|
72 |
+
assert trailing(-1) == 0
|
73 |
+
assert trailing(2) == 1
|
74 |
+
assert trailing(7) == 0
|
75 |
+
assert trailing(-7) == 0
|
76 |
+
for i in range(100):
|
77 |
+
assert trailing(1 << i) == i
|
78 |
+
assert trailing((1 << i) * 31337) == i
|
79 |
+
assert trailing(1 << 1000001) == 1000001
|
80 |
+
assert trailing((1 << 273956)*7**37) == 273956
|
81 |
+
# issue 12709
|
82 |
+
big = small_trailing[-1]*2
|
83 |
+
assert trailing(-big) == trailing(big)
|
84 |
+
assert bitcount(-big) == bitcount(big)
|
85 |
+
|
86 |
+
|
87 |
+
def test_multiplicity():
|
88 |
+
for b in range(2, 20):
|
89 |
+
for i in range(100):
|
90 |
+
assert multiplicity(b, b**i) == i
|
91 |
+
assert multiplicity(b, (b**i) * 23) == i
|
92 |
+
assert multiplicity(b, (b**i) * 1000249) == i
|
93 |
+
# Should be fast
|
94 |
+
assert multiplicity(10, 10**10023) == 10023
|
95 |
+
# Should exit quickly
|
96 |
+
assert multiplicity(10**10, 10**10) == 1
|
97 |
+
# Should raise errors for bad input
|
98 |
+
raises(ValueError, lambda: multiplicity(1, 1))
|
99 |
+
raises(ValueError, lambda: multiplicity(1, 2))
|
100 |
+
raises(ValueError, lambda: multiplicity(1.3, 2))
|
101 |
+
raises(ValueError, lambda: multiplicity(2, 0))
|
102 |
+
raises(ValueError, lambda: multiplicity(1.3, 0))
|
103 |
+
|
104 |
+
# handles Rationals
|
105 |
+
assert multiplicity(10, Rational(30, 7)) == 1
|
106 |
+
assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
|
107 |
+
assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
|
108 |
+
assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
|
109 |
+
assert multiplicity(3, Rational(1, 9)) == -2
|
110 |
+
|
111 |
+
|
112 |
+
def test_multiplicity_in_factorial():
|
113 |
+
n = fac(1000)
|
114 |
+
for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96):
|
115 |
+
assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000)
|
116 |
+
|
117 |
+
|
118 |
+
def test_perfect_power():
|
119 |
+
raises(ValueError, lambda: perfect_power(0.1))
|
120 |
+
assert perfect_power(0) is False
|
121 |
+
assert perfect_power(1) is False
|
122 |
+
assert perfect_power(2) is False
|
123 |
+
assert perfect_power(3) is False
|
124 |
+
assert perfect_power(4) == (2, 2)
|
125 |
+
assert perfect_power(14) is False
|
126 |
+
assert perfect_power(25) == (5, 2)
|
127 |
+
assert perfect_power(22) is False
|
128 |
+
assert perfect_power(22, [2]) is False
|
129 |
+
assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
|
130 |
+
assert perfect_power(137**(3*5*13) + 1) is False
|
131 |
+
assert perfect_power(137**(3*5*13) - 1) is False
|
132 |
+
assert perfect_power(103005006004**7) == (103005006004, 7)
|
133 |
+
assert perfect_power(103005006004**7 + 1) is False
|
134 |
+
assert perfect_power(103005006004**7 - 1) is False
|
135 |
+
assert perfect_power(103005006004**12) == (103005006004, 12)
|
136 |
+
assert perfect_power(103005006004**12 + 1) is False
|
137 |
+
assert perfect_power(103005006004**12 - 1) is False
|
138 |
+
assert perfect_power(2**10007) == (2, 10007)
|
139 |
+
assert perfect_power(2**10007 + 1) is False
|
140 |
+
assert perfect_power(2**10007 - 1) is False
|
141 |
+
assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
|
142 |
+
assert perfect_power((9**99 + 1)**60 + 1) is False
|
143 |
+
assert perfect_power((9**99 + 1)**60 - 1) is False
|
144 |
+
assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
|
145 |
+
assert perfect_power(10**100000) == (10, 100000)
|
146 |
+
assert perfect_power(10**100001) == (10, 100001)
|
147 |
+
assert perfect_power(13**4, [3, 5]) is False
|
148 |
+
assert perfect_power(3**4, [3, 10], factor=0) is False
|
149 |
+
assert perfect_power(3**3*5**3) == (15, 3)
|
150 |
+
assert perfect_power(2**3*5**5) is False
|
151 |
+
assert perfect_power(2*13**4) is False
|
152 |
+
assert perfect_power(2**5*3**3) is False
|
153 |
+
t = 2**24
|
154 |
+
for d in divisors(24):
|
155 |
+
m = perfect_power(t*3**d)
|
156 |
+
assert m and m[1] == d or d == 1
|
157 |
+
m = perfect_power(t*3**d, big=False)
|
158 |
+
assert m and m[1] == 2 or d == 1 or d == 3, (d, m)
|
159 |
+
|
160 |
+
# negatives and non-integer rationals
|
161 |
+
assert perfect_power(-4) is False
|
162 |
+
assert perfect_power(-8) == (-2, 3)
|
163 |
+
assert perfect_power(Rational(1, 2)**3) == (S.Half, 3)
|
164 |
+
assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3)
|
165 |
+
|
166 |
+
|
167 |
+
@slow
|
168 |
+
def test_factorint():
|
169 |
+
assert primefactors(123456) == [2, 3, 643]
|
170 |
+
assert factorint(0) == {0: 1}
|
171 |
+
assert factorint(1) == {}
|
172 |
+
assert factorint(-1) == {-1: 1}
|
173 |
+
assert factorint(-2) == {-1: 1, 2: 1}
|
174 |
+
assert factorint(-16) == {-1: 1, 2: 4}
|
175 |
+
assert factorint(2) == {2: 1}
|
176 |
+
assert factorint(126) == {2: 1, 3: 2, 7: 1}
|
177 |
+
assert factorint(123456) == {2: 6, 3: 1, 643: 1}
|
178 |
+
assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
|
179 |
+
assert factorint(64015937) == {7993: 1, 8009: 1}
|
180 |
+
assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
|
181 |
+
#issue 19683
|
182 |
+
assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
|
183 |
+
#issue 17676
|
184 |
+
assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
|
185 |
+
assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
|
186 |
+
assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}
|
187 |
+
|
188 |
+
assert factorint(0, multiple=True) == [0]
|
189 |
+
assert factorint(1, multiple=True) == []
|
190 |
+
assert factorint(-1, multiple=True) == [-1]
|
191 |
+
assert factorint(-2, multiple=True) == [-1, 2]
|
192 |
+
assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
|
193 |
+
assert factorint(2, multiple=True) == [2]
|
194 |
+
assert factorint(24, multiple=True) == [2, 2, 2, 3]
|
195 |
+
assert factorint(126, multiple=True) == [2, 3, 3, 7]
|
196 |
+
assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
|
197 |
+
assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
|
198 |
+
assert factorint(64015937, multiple=True) == [7993, 8009]
|
199 |
+
assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
|
200 |
+
|
201 |
+
assert factorint(fac(1, evaluate=False)) == {}
|
202 |
+
assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
|
203 |
+
assert factorint(fac(15, evaluate=False)) == \
|
204 |
+
{2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
|
205 |
+
assert factorint(fac(20, evaluate=False)) == \
|
206 |
+
{2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
|
207 |
+
assert factorint(fac(23, evaluate=False)) == \
|
208 |
+
{2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}
|
209 |
+
|
210 |
+
assert multiproduct(factorint(fac(200))) == fac(200)
|
211 |
+
assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
|
212 |
+
for b, e in factorint(fac(150)).items():
|
213 |
+
assert e == fac_multiplicity(150, b)
|
214 |
+
for b, e in factorint(fac(150, evaluate=False)).items():
|
215 |
+
assert e == fac_multiplicity(150, b)
|
216 |
+
assert factorint(103005006059**7) == {103005006059: 7}
|
217 |
+
assert factorint(31337**191) == {31337: 191}
|
218 |
+
assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
|
219 |
+
{2: 1000, 3: 500, 257: 127, 383: 60}
|
220 |
+
assert len(factorint(fac(10000))) == 1229
|
221 |
+
assert len(factorint(fac(10000, evaluate=False))) == 1229
|
222 |
+
assert factorint(12932983746293756928584532764589230) == \
|
223 |
+
{2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
|
224 |
+
assert factorint(727719592270351) == {727719592270351: 1}
|
225 |
+
assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
|
226 |
+
for n in range(60000):
|
227 |
+
assert multiproduct(factorint(n)) == n
|
228 |
+
assert pollard_rho(2**64 + 1, seed=1) == 274177
|
229 |
+
assert pollard_rho(19, seed=1) is None
|
230 |
+
assert factorint(3, limit=2) == {3: 1}
|
231 |
+
assert factorint(12345) == {3: 1, 5: 1, 823: 1}
|
232 |
+
assert factorint(
|
233 |
+
12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit
|
234 |
+
assert factorint(1, limit=1) == {}
|
235 |
+
assert factorint(0, 3) == {0: 1}
|
236 |
+
assert factorint(12, limit=1) == {12: 1}
|
237 |
+
assert factorint(30, limit=2) == {2: 1, 15: 1}
|
238 |
+
assert factorint(16, limit=2) == {2: 4}
|
239 |
+
assert factorint(124, limit=3) == {2: 2, 31: 1}
|
240 |
+
assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
|
241 |
+
p1 = nextprime(2**32)
|
242 |
+
p2 = nextprime(2**16)
|
243 |
+
p3 = nextprime(p2)
|
244 |
+
assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
|
245 |
+
assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
|
246 |
+
assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
|
247 |
+
assert factorint(primorial(17) + 1, use_pm1=0) == \
|
248 |
+
{int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
|
249 |
+
# when prime b is closer than approx sqrt(8*p) to prime p then they are
|
250 |
+
# "close" and have a trivial factorization
|
251 |
+
a = nextprime(2**2**8) # 78 digits
|
252 |
+
b = nextprime(a + 2**2**4)
|
253 |
+
assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
|
254 |
+
|
255 |
+
raises(ValueError, lambda: pollard_rho(4))
|
256 |
+
raises(ValueError, lambda: pollard_pm1(3))
|
257 |
+
raises(ValueError, lambda: pollard_pm1(10, B=2))
|
258 |
+
# verbose coverage
|
259 |
+
n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
|
260 |
+
assert 'with primes' in capture(lambda: factorint(n, verbose=1))
|
261 |
+
capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
|
262 |
+
|
263 |
+
n = nextprime(2**17)
|
264 |
+
capture(lambda: factorint(n**3, verbose=1)) # perfect power termination
|
265 |
+
capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg
|
266 |
+
|
267 |
+
# exceed 1st
|
268 |
+
n = nextprime(2**17)
|
269 |
+
n *= nextprime(n)
|
270 |
+
assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
|
271 |
+
n *= nextprime(n)
|
272 |
+
assert len(factorint(n)) == 3
|
273 |
+
assert len(factorint(n, limit=p1)) == 3
|
274 |
+
n *= nextprime(2*n)
|
275 |
+
# exceed 2nd
|
276 |
+
assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
|
277 |
+
assert capture(
|
278 |
+
lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
|
279 |
+
# non-prime pm1 result
|
280 |
+
n = nextprime(8069)
|
281 |
+
n *= nextprime(2*n)*nextprime(2*n, 2)
|
282 |
+
capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result
|
283 |
+
# factor fermat composite
|
284 |
+
p1 = nextprime(2**17)
|
285 |
+
p2 = nextprime(2*p1)
|
286 |
+
assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
|
287 |
+
# Test for non integer input
|
288 |
+
raises(ValueError, lambda: factorint(4.5))
|
289 |
+
# test dict/Dict input
|
290 |
+
sans = '2**10*3**3'
|
291 |
+
n = {4: 2, 12: 3}
|
292 |
+
assert str(factorint(n)) == sans
|
293 |
+
assert str(factorint(Dict(n))) == sans
|
294 |
+
|
295 |
+
|
296 |
+
def test_divisors_and_divisor_count():
|
297 |
+
assert divisors(-1) == [1]
|
298 |
+
assert divisors(0) == []
|
299 |
+
assert divisors(1) == [1]
|
300 |
+
assert divisors(2) == [1, 2]
|
301 |
+
assert divisors(3) == [1, 3]
|
302 |
+
assert divisors(17) == [1, 17]
|
303 |
+
assert divisors(10) == [1, 2, 5, 10]
|
304 |
+
assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
|
305 |
+
assert divisors(101) == [1, 101]
|
306 |
+
|
307 |
+
assert divisor_count(0) == 0
|
308 |
+
assert divisor_count(-1) == 1
|
309 |
+
assert divisor_count(1) == 1
|
310 |
+
assert divisor_count(6) == 4
|
311 |
+
assert divisor_count(12) == 6
|
312 |
+
|
313 |
+
assert divisor_count(180, 3) == divisor_count(180//3)
|
314 |
+
assert divisor_count(2*3*5, 7) == 0
|
315 |
+
|
316 |
+
|
317 |
+
def test_proper_divisors_and_proper_divisor_count():
|
318 |
+
assert proper_divisors(-1) == []
|
319 |
+
assert proper_divisors(0) == []
|
320 |
+
assert proper_divisors(1) == []
|
321 |
+
assert proper_divisors(2) == [1]
|
322 |
+
assert proper_divisors(3) == [1]
|
323 |
+
assert proper_divisors(17) == [1]
|
324 |
+
assert proper_divisors(10) == [1, 2, 5]
|
325 |
+
assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50]
|
326 |
+
assert proper_divisors(1000000007) == [1]
|
327 |
+
|
328 |
+
assert proper_divisor_count(0) == 0
|
329 |
+
assert proper_divisor_count(-1) == 0
|
330 |
+
assert proper_divisor_count(1) == 0
|
331 |
+
assert proper_divisor_count(36) == 8
|
332 |
+
assert proper_divisor_count(2*3*5) == 7
|
333 |
+
|
334 |
+
|
335 |
+
def test_udivisors_and_udivisor_count():
|
336 |
+
assert udivisors(-1) == [1]
|
337 |
+
assert udivisors(0) == []
|
338 |
+
assert udivisors(1) == [1]
|
339 |
+
assert udivisors(2) == [1, 2]
|
340 |
+
assert udivisors(3) == [1, 3]
|
341 |
+
assert udivisors(17) == [1, 17]
|
342 |
+
assert udivisors(10) == [1, 2, 5, 10]
|
343 |
+
assert udivisors(100) == [1, 4, 25, 100]
|
344 |
+
assert udivisors(101) == [1, 101]
|
345 |
+
assert udivisors(1000) == [1, 8, 125, 1000]
|
346 |
+
|
347 |
+
assert udivisor_count(0) == 0
|
348 |
+
assert udivisor_count(-1) == 1
|
349 |
+
assert udivisor_count(1) == 1
|
350 |
+
assert udivisor_count(6) == 4
|
351 |
+
assert udivisor_count(12) == 4
|
352 |
+
|
353 |
+
assert udivisor_count(180) == 8
|
354 |
+
assert udivisor_count(2*3*5*7) == 16
|
355 |
+
|
356 |
+
|
357 |
+
def test_issue_6981():
|
358 |
+
S = set(divisors(4)).union(set(divisors(Integer(2))))
|
359 |
+
assert S == {1,2,4}
|
360 |
+
|
361 |
+
|
362 |
+
def test_totient():
|
363 |
+
assert [totient(k) for k in range(1, 12)] == \
|
364 |
+
[1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10]
|
365 |
+
assert totient(5005) == 2880
|
366 |
+
assert totient(5006) == 2502
|
367 |
+
assert totient(5009) == 5008
|
368 |
+
assert totient(2**100) == 2**99
|
369 |
+
|
370 |
+
raises(ValueError, lambda: totient(30.1))
|
371 |
+
raises(ValueError, lambda: totient(20.001))
|
372 |
+
|
373 |
+
m = Symbol("m", integer=True)
|
374 |
+
assert totient(m)
|
375 |
+
assert totient(m).subs(m, 3**10) == 3**10 - 3**9
|
376 |
+
assert summation(totient(m), (m, 1, 11)) == 42
|
377 |
+
|
378 |
+
n = Symbol("n", integer=True, positive=True)
|
379 |
+
assert totient(n).is_integer
|
380 |
+
|
381 |
+
x=Symbol("x", integer=False)
|
382 |
+
raises(ValueError, lambda: totient(x))
|
383 |
+
|
384 |
+
y=Symbol("y", positive=False)
|
385 |
+
raises(ValueError, lambda: totient(y))
|
386 |
+
|
387 |
+
z=Symbol("z", positive=True, integer=True)
|
388 |
+
raises(ValueError, lambda: totient(2**(-z)))
|
389 |
+
|
390 |
+
|
391 |
+
def test_reduced_totient():
|
392 |
+
assert [reduced_totient(k) for k in range(1, 16)] == \
|
393 |
+
[1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4]
|
394 |
+
assert reduced_totient(5005) == 60
|
395 |
+
assert reduced_totient(5006) == 2502
|
396 |
+
assert reduced_totient(5009) == 5008
|
397 |
+
assert reduced_totient(2**100) == 2**98
|
398 |
+
|
399 |
+
m = Symbol("m", integer=True)
|
400 |
+
assert reduced_totient(m)
|
401 |
+
assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9
|
402 |
+
assert summation(reduced_totient(m), (m, 1, 16)) == 68
|
403 |
+
|
404 |
+
n = Symbol("n", integer=True, positive=True)
|
405 |
+
assert reduced_totient(n).is_integer
|
406 |
+
|
407 |
+
|
408 |
+
def test_divisor_sigma():
|
409 |
+
assert [divisor_sigma(k) for k in range(1, 12)] == \
|
410 |
+
[1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12]
|
411 |
+
assert [divisor_sigma(k, 2) for k in range(1, 12)] == \
|
412 |
+
[1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122]
|
413 |
+
assert divisor_sigma(23450) == 50592
|
414 |
+
assert divisor_sigma(23450, 0) == 24
|
415 |
+
assert divisor_sigma(23450, 1) == 50592
|
416 |
+
assert divisor_sigma(23450, 2) == 730747500
|
417 |
+
assert divisor_sigma(23450, 3) == 14666785333344
|
418 |
+
|
419 |
+
a = Symbol("a", prime=True)
|
420 |
+
b = Symbol("b", prime=True)
|
421 |
+
j = Symbol("j", integer=True, positive=True)
|
422 |
+
k = Symbol("k", integer=True, positive=True)
|
423 |
+
assert divisor_sigma(a**j*b**k) == (a**(j + 1) - 1)*(b**(k + 1) - 1)/((a - 1)*(b - 1))
|
424 |
+
assert divisor_sigma(a**j*b**k, 2) == (a**(2*j + 2) - 1)*(b**(2*k + 2) - 1)/((a**2 - 1)*(b**2 - 1))
|
425 |
+
assert divisor_sigma(a**j*b**k, 0) == (j + 1)*(k + 1)
|
426 |
+
|
427 |
+
m = Symbol("m", integer=True)
|
428 |
+
k = Symbol("k", integer=True)
|
429 |
+
assert divisor_sigma(m)
|
430 |
+
assert divisor_sigma(m, k)
|
431 |
+
assert divisor_sigma(m).subs(m, 3**10) == 88573
|
432 |
+
assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597
|
433 |
+
assert summation(divisor_sigma(m), (m, 1, 11)) == 99
|
434 |
+
|
435 |
+
|
436 |
+
def test_udivisor_sigma():
|
437 |
+
assert [udivisor_sigma(k) for k in range(1, 12)] == \
|
438 |
+
[1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12]
|
439 |
+
assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \
|
440 |
+
[1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332]
|
441 |
+
assert udivisor_sigma(23450) == 42432
|
442 |
+
assert udivisor_sigma(23450, 0) == 16
|
443 |
+
assert udivisor_sigma(23450, 1) == 42432
|
444 |
+
assert udivisor_sigma(23450, 2) == 702685000
|
445 |
+
assert udivisor_sigma(23450, 4) == 321426961814978248
|
446 |
+
|
447 |
+
m = Symbol("m", integer=True)
|
448 |
+
k = Symbol("k", integer=True)
|
449 |
+
assert udivisor_sigma(m)
|
450 |
+
assert udivisor_sigma(m, k)
|
451 |
+
assert udivisor_sigma(m).subs(m, 4**9) == 262145
|
452 |
+
assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737
|
453 |
+
assert summation(udivisor_sigma(m), (m, 2, 15)) == 169
|
454 |
+
|
455 |
+
|
456 |
+
def test_issue_4356():
|
457 |
+
assert factorint(1030903) == {53: 2, 367: 1}
|
458 |
+
|
459 |
+
|
460 |
+
def test_divisors():
|
461 |
+
assert divisors(28) == [1, 2, 4, 7, 14, 28]
|
462 |
+
assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105]
|
463 |
+
assert divisors(0) == []
|
464 |
+
|
465 |
+
|
466 |
+
def test_divisor_count():
|
467 |
+
assert divisor_count(0) == 0
|
468 |
+
assert divisor_count(6) == 4
|
469 |
+
|
470 |
+
|
471 |
+
def test_proper_divisors():
|
472 |
+
assert proper_divisors(-1) == []
|
473 |
+
assert proper_divisors(28) == [1, 2, 4, 7, 14]
|
474 |
+
assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35]
|
475 |
+
|
476 |
+
|
477 |
+
def test_proper_divisor_count():
|
478 |
+
assert proper_divisor_count(6) == 3
|
479 |
+
assert proper_divisor_count(108) == 11
|
480 |
+
|
481 |
+
|
482 |
+
def test_antidivisors():
|
483 |
+
assert antidivisors(-1) == []
|
484 |
+
assert antidivisors(-3) == [2]
|
485 |
+
assert antidivisors(14) == [3, 4, 9]
|
486 |
+
assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
|
487 |
+
assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
|
488 |
+
assert antidivisors(393216) == [262144]
|
489 |
+
assert sorted(x for x in antidivisors(3*5*7, 1)) == \
|
490 |
+
[2, 6, 10, 11, 14, 19, 30, 42, 70]
|
491 |
+
assert antidivisors(1) == []
|
492 |
+
|
493 |
+
|
494 |
+
def test_antidivisor_count():
|
495 |
+
assert antidivisor_count(0) == 0
|
496 |
+
assert antidivisor_count(-1) == 0
|
497 |
+
assert antidivisor_count(-4) == 1
|
498 |
+
assert antidivisor_count(20) == 3
|
499 |
+
assert antidivisor_count(25) == 5
|
500 |
+
assert antidivisor_count(38) == 7
|
501 |
+
assert antidivisor_count(180) == 6
|
502 |
+
assert antidivisor_count(2*3*5) == 3
|
503 |
+
|
504 |
+
|
505 |
+
def test_smoothness_and_smoothness_p():
|
506 |
+
assert smoothness(1) == (1, 1)
|
507 |
+
assert smoothness(2**4*3**2) == (3, 16)
|
508 |
+
|
509 |
+
assert smoothness_p(10431, m=1) == \
|
510 |
+
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
|
511 |
+
assert smoothness_p(10431) == \
|
512 |
+
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
|
513 |
+
assert smoothness_p(10431, power=1) == \
|
514 |
+
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
|
515 |
+
assert smoothness_p(21477639576571, visual=1) == \
|
516 |
+
'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
|
517 |
+
'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
|
518 |
+
|
519 |
+
|
520 |
+
def test_visual_factorint():
|
521 |
+
assert factorint(1, visual=1) == 1
|
522 |
+
forty2 = factorint(42, visual=True)
|
523 |
+
assert type(forty2) == Mul
|
524 |
+
assert str(forty2) == '2**1*3**1*7**1'
|
525 |
+
assert factorint(1, visual=True) is S.One
|
526 |
+
no = {"evaluate": False}
|
527 |
+
assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
|
528 |
+
Pow(3, 2, **no),
|
529 |
+
Pow(7, 2, **no), **no)
|
530 |
+
assert -1 in factorint(-42, visual=True).args
|
531 |
+
|
532 |
+
|
533 |
+
def test_factorrat():
|
534 |
+
assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
|
535 |
+
assert str(factorrat(Rational(1, 1), visual=True)) == '1'
|
536 |
+
assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
|
537 |
+
assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)'
|
538 |
+
assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)'
|
539 |
+
|
540 |
+
assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
|
541 |
+
assert factorrat(Rational(1, 1), multiple=True) == []
|
542 |
+
assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5]
|
543 |
+
assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5]
|
544 |
+
assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3]
|
545 |
+
assert factorrat(S(-25)/14/9, multiple=True) == \
|
546 |
+
[-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5]
|
547 |
+
|
548 |
+
|
549 |
+
def test_visual_io():
|
550 |
+
sm = smoothness_p
|
551 |
+
fi = factorint
|
552 |
+
# with smoothness_p
|
553 |
+
n = 124
|
554 |
+
d = fi(n)
|
555 |
+
m = fi(d, visual=True)
|
556 |
+
t = sm(n)
|
557 |
+
s = sm(t)
|
558 |
+
for th in [d, s, t, n, m]:
|
559 |
+
assert sm(th, visual=True) == s
|
560 |
+
assert sm(th, visual=1) == s
|
561 |
+
for th in [d, s, t, n, m]:
|
562 |
+
assert sm(th, visual=False) == t
|
563 |
+
assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
|
564 |
+
assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
|
565 |
+
|
566 |
+
# with factorint
|
567 |
+
for th in [d, m, n]:
|
568 |
+
assert fi(th, visual=True) == m
|
569 |
+
assert fi(th, visual=1) == m
|
570 |
+
for th in [d, m, n]:
|
571 |
+
assert fi(th, visual=False) == d
|
572 |
+
assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
|
573 |
+
assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
|
574 |
+
|
575 |
+
# test reevaluation
|
576 |
+
no = {"evaluate": False}
|
577 |
+
assert sm({4: 2}, visual=False) == sm(16)
|
578 |
+
assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
|
579 |
+
visual=False) == sm(2**10)
|
580 |
+
|
581 |
+
assert fi({4: 2}, visual=False) == fi(16)
|
582 |
+
assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
|
583 |
+
visual=False) == fi(2**10)
|
584 |
+
|
585 |
+
|
586 |
+
def test_core():
|
587 |
+
assert core(35**13, 10) == 42875
|
588 |
+
assert core(210**2) == 1
|
589 |
+
assert core(7776, 3) == 36
|
590 |
+
assert core(10**27, 22) == 10**5
|
591 |
+
assert core(537824) == 14
|
592 |
+
assert core(1, 6) == 1
|
593 |
+
|
594 |
+
|
595 |
+
def test_primenu():
|
596 |
+
assert primenu(2) == 1
|
597 |
+
assert primenu(2 * 3) == 2
|
598 |
+
assert primenu(2 * 3 * 5) == 3
|
599 |
+
assert primenu(3 * 25) == primenu(3) + primenu(25)
|
600 |
+
assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
|
601 |
+
assert primenu(fac(50)) == 15
|
602 |
+
assert primenu(2 ** 9941 - 1) == 1
|
603 |
+
n = Symbol('n', integer=True)
|
604 |
+
assert primenu(n)
|
605 |
+
assert primenu(n).subs(n, 2 ** 31 - 1) == 1
|
606 |
+
assert summation(primenu(n), (n, 2, 30)) == 43
|
607 |
+
|
608 |
+
|
609 |
+
def test_primeomega():
|
610 |
+
assert primeomega(2) == 1
|
611 |
+
assert primeomega(2 * 2) == 2
|
612 |
+
assert primeomega(2 * 2 * 3) == 3
|
613 |
+
assert primeomega(3 * 25) == primeomega(3) + primeomega(25)
|
614 |
+
assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1]
|
615 |
+
assert primeomega(fac(50)) == 108
|
616 |
+
assert primeomega(2 ** 9941 - 1) == 1
|
617 |
+
n = Symbol('n', integer=True)
|
618 |
+
assert primeomega(n)
|
619 |
+
assert primeomega(n).subs(n, 2 ** 31 - 1) == 1
|
620 |
+
assert summation(primeomega(n), (n, 2, 30)) == 59
|
621 |
+
|
622 |
+
|
623 |
+
def test_mersenne_prime_exponent():
|
624 |
+
assert mersenne_prime_exponent(1) == 2
|
625 |
+
assert mersenne_prime_exponent(4) == 7
|
626 |
+
assert mersenne_prime_exponent(10) == 89
|
627 |
+
assert mersenne_prime_exponent(25) == 21701
|
628 |
+
raises(ValueError, lambda: mersenne_prime_exponent(52))
|
629 |
+
raises(ValueError, lambda: mersenne_prime_exponent(0))
|
630 |
+
|
631 |
+
|
632 |
+
def test_is_perfect():
|
633 |
+
assert is_perfect(6) is True
|
634 |
+
assert is_perfect(15) is False
|
635 |
+
assert is_perfect(28) is True
|
636 |
+
assert is_perfect(400) is False
|
637 |
+
assert is_perfect(496) is True
|
638 |
+
assert is_perfect(8128) is True
|
639 |
+
assert is_perfect(10000) is False
|
640 |
+
|
641 |
+
|
642 |
+
def test_is_mersenne_prime():
|
643 |
+
assert is_mersenne_prime(10) is False
|
644 |
+
assert is_mersenne_prime(127) is True
|
645 |
+
assert is_mersenne_prime(511) is False
|
646 |
+
assert is_mersenne_prime(131071) is True
|
647 |
+
assert is_mersenne_prime(2147483647) is True
|
648 |
+
|
649 |
+
|
650 |
+
def test_is_abundant():
|
651 |
+
assert is_abundant(10) is False
|
652 |
+
assert is_abundant(12) is True
|
653 |
+
assert is_abundant(18) is True
|
654 |
+
assert is_abundant(21) is False
|
655 |
+
assert is_abundant(945) is True
|
656 |
+
|
657 |
+
|
658 |
+
def test_is_deficient():
|
659 |
+
assert is_deficient(10) is True
|
660 |
+
assert is_deficient(22) is True
|
661 |
+
assert is_deficient(56) is False
|
662 |
+
assert is_deficient(20) is False
|
663 |
+
assert is_deficient(36) is False
|
664 |
+
|
665 |
+
|
666 |
+
def test_is_amicable():
|
667 |
+
assert is_amicable(173, 129) is False
|
668 |
+
assert is_amicable(220, 284) is True
|
669 |
+
assert is_amicable(8756, 8756) is False
|
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))
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py
ADDED
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import (I, Rational, nan, zoo)
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import Symbol
|
4 |
+
from sympy.ntheory.generate import (sieve, Sieve)
|
5 |
+
from sympy.series.limits import limit
|
6 |
+
|
7 |
+
from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
|
8 |
+
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
|
9 |
+
from sympy.ntheory.generate import cycle_length
|
10 |
+
from sympy.ntheory.primetest import mr
|
11 |
+
from sympy.testing.pytest import raises
|
12 |
+
|
13 |
+
def test_prime():
|
14 |
+
assert prime(1) == 2
|
15 |
+
assert prime(2) == 3
|
16 |
+
assert prime(5) == 11
|
17 |
+
assert prime(11) == 31
|
18 |
+
assert prime(57) == 269
|
19 |
+
assert prime(296) == 1949
|
20 |
+
assert prime(559) == 4051
|
21 |
+
assert prime(3000) == 27449
|
22 |
+
assert prime(4096) == 38873
|
23 |
+
assert prime(9096) == 94321
|
24 |
+
assert prime(25023) == 287341
|
25 |
+
assert prime(10000000) == 179424673 # issue #20951
|
26 |
+
assert prime(99999999) == 2038074739
|
27 |
+
raises(ValueError, lambda: prime(0))
|
28 |
+
sieve.extend(3000)
|
29 |
+
assert prime(401) == 2749
|
30 |
+
raises(ValueError, lambda: prime(-1))
|
31 |
+
|
32 |
+
|
33 |
+
def test_primepi():
|
34 |
+
assert primepi(-1) == 0
|
35 |
+
assert primepi(1) == 0
|
36 |
+
assert primepi(2) == 1
|
37 |
+
assert primepi(Rational(7, 2)) == 2
|
38 |
+
assert primepi(3.5) == 2
|
39 |
+
assert primepi(5) == 3
|
40 |
+
assert primepi(11) == 5
|
41 |
+
assert primepi(57) == 16
|
42 |
+
assert primepi(296) == 62
|
43 |
+
assert primepi(559) == 102
|
44 |
+
assert primepi(3000) == 430
|
45 |
+
assert primepi(4096) == 564
|
46 |
+
assert primepi(9096) == 1128
|
47 |
+
assert primepi(25023) == 2763
|
48 |
+
assert primepi(10**8) == 5761455
|
49 |
+
assert primepi(253425253) == 13856396
|
50 |
+
assert primepi(8769575643) == 401464322
|
51 |
+
sieve.extend(3000)
|
52 |
+
assert primepi(2000) == 303
|
53 |
+
|
54 |
+
n = Symbol('n')
|
55 |
+
assert primepi(n).subs(n, 2) == 1
|
56 |
+
|
57 |
+
r = Symbol('r', real=True)
|
58 |
+
assert primepi(r).subs(r, 2) == 1
|
59 |
+
|
60 |
+
assert primepi(S.Infinity) is S.Infinity
|
61 |
+
assert primepi(S.NegativeInfinity) == 0
|
62 |
+
|
63 |
+
assert limit(primepi(n), n, 100) == 25
|
64 |
+
|
65 |
+
raises(ValueError, lambda: primepi(I))
|
66 |
+
raises(ValueError, lambda: primepi(1 + I))
|
67 |
+
raises(ValueError, lambda: primepi(zoo))
|
68 |
+
raises(ValueError, lambda: primepi(nan))
|
69 |
+
|
70 |
+
|
71 |
+
def test_composite():
|
72 |
+
from sympy.ntheory.generate import sieve
|
73 |
+
sieve._reset()
|
74 |
+
assert composite(1) == 4
|
75 |
+
assert composite(2) == 6
|
76 |
+
assert composite(5) == 10
|
77 |
+
assert composite(11) == 20
|
78 |
+
assert composite(41) == 58
|
79 |
+
assert composite(57) == 80
|
80 |
+
assert composite(296) == 370
|
81 |
+
assert composite(559) == 684
|
82 |
+
assert composite(3000) == 3488
|
83 |
+
assert composite(4096) == 4736
|
84 |
+
assert composite(9096) == 10368
|
85 |
+
assert composite(25023) == 28088
|
86 |
+
sieve.extend(3000)
|
87 |
+
assert composite(1957) == 2300
|
88 |
+
assert composite(2568) == 2998
|
89 |
+
raises(ValueError, lambda: composite(0))
|
90 |
+
|
91 |
+
|
92 |
+
def test_compositepi():
|
93 |
+
assert compositepi(1) == 0
|
94 |
+
assert compositepi(2) == 0
|
95 |
+
assert compositepi(5) == 1
|
96 |
+
assert compositepi(11) == 5
|
97 |
+
assert compositepi(57) == 40
|
98 |
+
assert compositepi(296) == 233
|
99 |
+
assert compositepi(559) == 456
|
100 |
+
assert compositepi(3000) == 2569
|
101 |
+
assert compositepi(4096) == 3531
|
102 |
+
assert compositepi(9096) == 7967
|
103 |
+
assert compositepi(25023) == 22259
|
104 |
+
assert compositepi(10**8) == 94238544
|
105 |
+
assert compositepi(253425253) == 239568856
|
106 |
+
assert compositepi(8769575643) == 8368111320
|
107 |
+
sieve.extend(3000)
|
108 |
+
assert compositepi(2321) == 1976
|
109 |
+
|
110 |
+
|
111 |
+
def test_generate():
|
112 |
+
from sympy.ntheory.generate import sieve
|
113 |
+
sieve._reset()
|
114 |
+
assert nextprime(-4) == 2
|
115 |
+
assert nextprime(2) == 3
|
116 |
+
assert nextprime(5) == 7
|
117 |
+
assert nextprime(12) == 13
|
118 |
+
assert prevprime(3) == 2
|
119 |
+
assert prevprime(7) == 5
|
120 |
+
assert prevprime(13) == 11
|
121 |
+
assert prevprime(19) == 17
|
122 |
+
assert prevprime(20) == 19
|
123 |
+
|
124 |
+
sieve.extend_to_no(9)
|
125 |
+
assert sieve._list[-1] == 23
|
126 |
+
|
127 |
+
assert sieve._list[-1] < 31
|
128 |
+
assert 31 in sieve
|
129 |
+
|
130 |
+
assert nextprime(90) == 97
|
131 |
+
assert nextprime(10**40) == (10**40 + 121)
|
132 |
+
assert prevprime(97) == 89
|
133 |
+
assert prevprime(10**40) == (10**40 - 17)
|
134 |
+
|
135 |
+
assert list(sieve.primerange(10, 1)) == []
|
136 |
+
assert list(sieve.primerange(5, 9)) == [5, 7]
|
137 |
+
sieve._reset(prime=True)
|
138 |
+
assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
|
139 |
+
assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
|
140 |
+
assert list(sieve.primerange(8)) == [2, 3, 5, 7]
|
141 |
+
assert list(sieve.primerange(-2)) == []
|
142 |
+
assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
|
143 |
+
assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
|
144 |
+
|
145 |
+
assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
|
146 |
+
sieve._reset(totient=True)
|
147 |
+
assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
|
148 |
+
assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
|
149 |
+
assert list(sieve.totientrange(0, 1)) == []
|
150 |
+
assert list(sieve.totientrange(1, 2)) == [1]
|
151 |
+
|
152 |
+
assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
|
153 |
+
sieve._reset(mobius=True)
|
154 |
+
assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
|
155 |
+
assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
|
156 |
+
assert list(sieve.mobiusrange(0, 1)) == []
|
157 |
+
assert list(sieve.mobiusrange(1, 2)) == [1]
|
158 |
+
|
159 |
+
assert list(primerange(10, 1)) == []
|
160 |
+
assert list(primerange(2, 7)) == [2, 3, 5]
|
161 |
+
assert list(primerange(2, 10)) == [2, 3, 5, 7]
|
162 |
+
assert list(primerange(1050, 1100)) == [1051, 1061,
|
163 |
+
1063, 1069, 1087, 1091, 1093, 1097]
|
164 |
+
s = Sieve()
|
165 |
+
for i in range(30, 2350, 376):
|
166 |
+
for j in range(2, 5096, 1139):
|
167 |
+
A = list(s.primerange(i, i + j))
|
168 |
+
B = list(primerange(i, i + j))
|
169 |
+
assert A == B
|
170 |
+
s = Sieve()
|
171 |
+
assert s[10] == 29
|
172 |
+
|
173 |
+
assert nextprime(2, 2) == 5
|
174 |
+
|
175 |
+
raises(ValueError, lambda: totient(0))
|
176 |
+
|
177 |
+
raises(ValueError, lambda: reduced_totient(0))
|
178 |
+
|
179 |
+
raises(ValueError, lambda: primorial(0))
|
180 |
+
|
181 |
+
assert mr(1, [2]) is False
|
182 |
+
|
183 |
+
func = lambda i: (i**2 + 1) % 51
|
184 |
+
assert next(cycle_length(func, 4)) == (6, 2)
|
185 |
+
assert list(cycle_length(func, 4, values=True)) == \
|
186 |
+
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
|
187 |
+
assert next(cycle_length(func, 4, nmax=5)) == (5, None)
|
188 |
+
assert list(cycle_length(func, 4, nmax=5, values=True)) == \
|
189 |
+
[17, 35, 2, 5, 26]
|
190 |
+
sieve.extend(3000)
|
191 |
+
assert nextprime(2968) == 2969
|
192 |
+
assert prevprime(2930) == 2927
|
193 |
+
raises(ValueError, lambda: prevprime(1))
|
194 |
+
raises(ValueError, lambda: prevprime(-4))
|
195 |
+
|
196 |
+
|
197 |
+
def test_randprime():
|
198 |
+
assert randprime(10, 1) is None
|
199 |
+
assert randprime(3, -3) is None
|
200 |
+
assert randprime(2, 3) == 2
|
201 |
+
assert randprime(1, 3) == 2
|
202 |
+
assert randprime(3, 5) == 3
|
203 |
+
raises(ValueError, lambda: randprime(-12, -2))
|
204 |
+
raises(ValueError, lambda: randprime(-10, 0))
|
205 |
+
raises(ValueError, lambda: randprime(20, 22))
|
206 |
+
raises(ValueError, lambda: randprime(0, 2))
|
207 |
+
raises(ValueError, lambda: randprime(1, 2))
|
208 |
+
for a in [100, 300, 500, 250000]:
|
209 |
+
for b in [100, 300, 500, 250000]:
|
210 |
+
p = randprime(a, a + b)
|
211 |
+
assert a <= p < (a + b) and isprime(p)
|
212 |
+
|
213 |
+
|
214 |
+
def test_primorial():
|
215 |
+
assert primorial(1) == 2
|
216 |
+
assert primorial(1, nth=0) == 1
|
217 |
+
assert primorial(2) == 6
|
218 |
+
assert primorial(2, nth=0) == 2
|
219 |
+
assert primorial(4, nth=0) == 6
|
220 |
+
|
221 |
+
|
222 |
+
def test_search():
|
223 |
+
assert 2 in sieve
|
224 |
+
assert 2.1 not in sieve
|
225 |
+
assert 1 not in sieve
|
226 |
+
assert 2**1000 not in sieve
|
227 |
+
raises(ValueError, lambda: sieve.search(1))
|
228 |
+
|
229 |
+
|
230 |
+
def test_sieve_slice():
|
231 |
+
assert sieve[5] == 11
|
232 |
+
assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
|
233 |
+
assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
|
234 |
+
assert list(sieve[1:5]) == [2, 3, 5, 7]
|
235 |
+
raises(IndexError, lambda: sieve[:5])
|
236 |
+
raises(IndexError, lambda: sieve[0])
|
237 |
+
raises(IndexError, lambda: sieve[0:5])
|
238 |
+
|
239 |
+
def test_sieve_iter():
|
240 |
+
values = []
|
241 |
+
for value in sieve:
|
242 |
+
if value > 7:
|
243 |
+
break
|
244 |
+
values.append(value)
|
245 |
+
assert values == list(sieve[1:5])
|
246 |
+
|
247 |
+
|
248 |
+
def test_sieve_repr():
|
249 |
+
assert "sieve" in repr(sieve)
|
250 |
+
assert "prime" in repr(sieve)
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
|
2 |
+
from sympy.testing.pytest import raises
|
3 |
+
|
4 |
+
|
5 |
+
def test_crt():
|
6 |
+
def mcrt(m, v, r, symmetric=False):
|
7 |
+
assert crt(m, v, symmetric)[0] == r
|
8 |
+
mm, e, s = crt1(m)
|
9 |
+
assert crt2(m, v, mm, e, s, symmetric) == (r, mm)
|
10 |
+
|
11 |
+
mcrt([2, 3, 5], [0, 0, 0], 0)
|
12 |
+
mcrt([2, 3, 5], [1, 1, 1], 1)
|
13 |
+
|
14 |
+
mcrt([2, 3, 5], [-1, -1, -1], -1, True)
|
15 |
+
mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False)
|
16 |
+
|
17 |
+
assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800)
|
18 |
+
|
19 |
+
|
20 |
+
def test_modular():
|
21 |
+
assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140)
|
22 |
+
assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None
|
23 |
+
assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547)
|
24 |
+
assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547)
|
25 |
+
assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None
|
26 |
+
assert solve_congruence(
|
27 |
+
*list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547)
|
28 |
+
assert solve_congruence(
|
29 |
+
*list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
|
30 |
+
assert solve_congruence(
|
31 |
+
*list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
|
32 |
+
assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None
|
33 |
+
raises(
|
34 |
+
ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17]))))
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients)
|
2 |
+
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
|
3 |
+
|
4 |
+
|
5 |
+
def test_binomial_coefficients_list():
|
6 |
+
assert binomial_coefficients_list(0) == [1]
|
7 |
+
assert binomial_coefficients_list(1) == [1, 1]
|
8 |
+
assert binomial_coefficients_list(2) == [1, 2, 1]
|
9 |
+
assert binomial_coefficients_list(3) == [1, 3, 3, 1]
|
10 |
+
assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1]
|
11 |
+
assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1]
|
12 |
+
assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1]
|
13 |
+
|
14 |
+
|
15 |
+
def test_binomial_coefficients():
|
16 |
+
for n in range(15):
|
17 |
+
c = binomial_coefficients(n)
|
18 |
+
l = [c[k] for k in sorted(c)]
|
19 |
+
assert l == binomial_coefficients_list(n)
|
20 |
+
|
21 |
+
|
22 |
+
def test_multinomial_coefficients():
|
23 |
+
assert multinomial_coefficients(1, 1) == {(1,): 1}
|
24 |
+
assert multinomial_coefficients(1, 2) == {(2,): 1}
|
25 |
+
assert multinomial_coefficients(1, 3) == {(3,): 1}
|
26 |
+
assert multinomial_coefficients(2, 0) == {(0, 0): 1}
|
27 |
+
assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1}
|
28 |
+
assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2}
|
29 |
+
assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1,
|
30 |
+
(2, 1): 3}
|
31 |
+
assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1,
|
32 |
+
(0, 0, 1): 1}
|
33 |
+
assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1,
|
34 |
+
(1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1}
|
35 |
+
mc = multinomial_coefficients(3, 3)
|
36 |
+
assert mc == {(2, 1, 0): 3, (0, 3, 0): 1,
|
37 |
+
(1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1,
|
38 |
+
(2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1}
|
39 |
+
assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1}
|
40 |
+
assert dict(
|
41 |
+
multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1}
|
42 |
+
assert dict(multinomial_coefficients_iterator(2, 2)) == \
|
43 |
+
{(2, 0): 1, (0, 2): 1, (1, 1): 2}
|
44 |
+
assert dict(multinomial_coefficients_iterator(3, 3)) == mc
|
45 |
+
it = multinomial_coefficients_iterator(7, 2)
|
46 |
+
assert [next(it) for i in range(4)] == \
|
47 |
+
[((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2),
|
48 |
+
((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)]
|
venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.ntheory import npartitions
|
2 |
+
|
3 |
+
|
4 |
+
def test_partitions():
|
5 |
+
assert [npartitions(k) for k in range(13)] == \
|
6 |
+
[1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77]
|
7 |
+
assert npartitions(100) == 190569292
|
8 |
+
assert npartitions(200) == 3972999029388
|
9 |
+
assert npartitions(1000) == 24061467864032622473692149727991
|
10 |
+
assert npartitions(2000) == 4720819175619413888601432406799959512200344166
|
11 |
+
assert npartitions(10000) % 10**10 == 6916435144
|
12 |
+
assert npartitions(100000) % 10**10 == 9421098519
|