diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e050a5196fc4d524a6fa2288eea7f02f0b9a922 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__init__.py @@ -0,0 +1,67 @@ +""" +Number theory module (primes, etc) +""" + +from .generate import nextprime, prevprime, prime, primepi, primerange, \ + randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi +from .primetest import isprime, is_gaussian_prime +from .factor_ import divisors, proper_divisors, factorint, multiplicity, \ + multiplicity_in_factorial, perfect_power, pollard_pm1, pollard_rho, \ + primefactors, totient, trailing, \ + divisor_count, proper_divisor_count, divisor_sigma, factorrat, \ + reduced_totient, primenu, primeomega, mersenne_prime_exponent, \ + is_perfect, is_mersenne_prime, is_abundant, is_deficient, is_amicable, \ + abundance, dra, drm + +from .partitions_ import npartitions +from .residue_ntheory import is_primitive_root, is_quad_residue, \ + legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \ + primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \ + discrete_log, quadratic_congruence, polynomial_congruence +from .multinomial import binomial_coefficients, binomial_coefficients_list, \ + multinomial_coefficients +from .continued_fraction import continued_fraction_periodic, \ + continued_fraction_iterator, continued_fraction_reduce, \ + continued_fraction_convergents, continued_fraction +from .digits import count_digits, digits, is_palindromic +from .egyptian_fraction import egyptian_fraction +from .ecm import ecm +from .qs import qs +__all__ = [ + 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + + 'isprime', 'is_gaussian_prime', + + + 'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power', + 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', 'trailing', + 'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat', + 'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent', + 'is_perfect', 'is_mersenne_prime', 'is_abundant', 'is_deficient', 'is_amicable', + 'abundance', 'dra', 'drm', 'multiplicity_in_factorial', + + 'npartitions', + + 'is_primitive_root', 'is_quad_residue', 'legendre_symbol', + 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'mobius', 'discrete_log', 'quadratic_congruence', 'polynomial_congruence', + + 'binomial_coefficients', 'binomial_coefficients_list', + 'multinomial_coefficients', + + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', + + 'digits', + 'count_digits', + 'is_palindromic', + + 'egyptian_fraction', + + 'ecm', + + 'qs', +] diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ed5c277f568ffed53f03da6f7e0a8667fb9bba Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496387e88e15283916c87216f9c3be1da617acef Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29ae8e48b0a7d1ca3b54e18ab4273a5c2e9d3876 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccdc8ec359a0be1b92e0afc6e6a0ef7b53a13ba9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14476764e3362e929b0746e8127f9b108095a21 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ebab8a3f90c38ee24a9037f3a61115fede13ac1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..355bc6b247c7251e2f93c043fdb54932c8b86e40 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f80a182877fc10dd253a5bcbe7783b9d49da63 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..344d4fe5dcdcc7fc3ecdbb3db382cfb2974c1bfa Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efb231558dbcc3a5f6d346a7f0039ea090b62508 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ea5a86061d2c4ffd0262d4ee89187b7a160a62e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18be3ac0ad1df1e9acc4c53038d77c9c7a130026 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6790d11ee68f2739fa58817ece87b4fe4270c8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab16bb08387dfe9247c086903166e4dc228100c3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py new file mode 100644 index 0000000000000000000000000000000000000000..03a571b59d9b1608aa22cb8e7aff3010cda35633 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py @@ -0,0 +1,159 @@ +''' +This implementation is a heavily modified fixed point implementation of +BBP_formula for calculating the nth position of pi. The original hosted +at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python) + +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sub-license, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Modifications: + +1.Once the nth digit and desired number of digits is selected, the +number of digits of working precision is calculated to ensure that +the hexadecimal digits returned are accurate. This is calculated as + + int(math.log(start + prec)/math.log(16) + prec + 3) + --------------------------------------- -------- + / / + number of hex digits additional digits + +This was checked by the following code which completed without +errors (and dig are the digits included in the test_bbp.py file): + + for i in range(0,1000): + for j in range(1,1000): + a, b = pi_hex_digits(i, j), dig[i:i+j] + if a != b: + print('%s\n%s'%(a,b)) + +Deceasing the additional digits by 1 generated errors, so '3' is +the smallest additional precision needed to calculate the above +loop without errors. The following trailing 10 digits were also +checked to be accurate (and the times were slightly faster with +some of the constant modifications that were made): + + >> from time import time + >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t + ('e90c6cc0ac', 0.0) + >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t + ('26aab49ec6', 0.17100000381469727) + >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t + ('a22673c1a5', 4.7109999656677246) + >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t + ('9ffd342362', 59.985999822616577) + >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t + ('c1a42e06a1', 689.51800012588501) + +2. The while loop to evaluate whether the series has converged quits +when the addition amount `dt` has dropped to zero. + +3. the formatting string to convert the decimal to hexadecimal is +calculated for the given precision. + +4. pi_hex_digits(n) changed to have coefficient to the formula in an +array (perhaps just a matter of preference). + +''' + +import math +from sympy.utilities.misc import as_int + + +def _series(j, n, prec=14): + + # Left sum from the bbp algorithm + s = 0 + D = _dn(n, prec) + D4 = 4 * D + k = 0 + d = 8 * k + j + for k in range(n + 1): + s += (pow(16, n - k, d) << D4) // d + d += 8 + + # Right sum iterates to infinity for full precision, but we + # stop at the point where one iteration is beyond the precision + # specified. + + t = 0 + k = n + 1 + e = 4*(D + n - k) + d = 8 * k + j + while True: + dt = (1 << e) // d + if not dt: + break + t += dt + # k += 1 + e -= 4 + d += 8 + total = s + t + + return total + + +def pi_hex_digits(n, prec=14): + """Returns a string containing ``prec`` (default 14) digits + starting at the nth digit of pi in hex. Counting of digits + starts at 0 and the decimal is not counted, so for n = 0 the + returned value starts with 3; n = 1 corresponds to the first + digit past the decimal point (which in hex is 2). + + Examples + ======== + + >>> from sympy.ntheory.bbp_pi import pi_hex_digits + >>> pi_hex_digits(0) + '3243f6a8885a30' + >>> pi_hex_digits(0, 3) + '324' + + References + ========== + + .. [1] http://www.numberworld.org/digits/Pi/ + """ + n, prec = as_int(n), as_int(prec) + if n < 0: + raise ValueError('n cannot be negative') + if prec == 0: + return '' + + # main of implementation arrays holding formulae coefficients + n -= 1 + a = [4, 2, 1, 1] + j = [1, 4, 5, 6] + + #formulae + D = _dn(n, prec) + x = + (a[0]*_series(j[0], n, prec) + - a[1]*_series(j[1], n, prec) + - a[2]*_series(j[2], n, prec) + - a[3]*_series(j[3], n, prec)) & (16**D - 1) + + s = ("%0" + "%ix" % prec) % (x // 16**(D - prec)) + return s + + +def _dn(n, prec): + # controller for n dependence on precision + # n = starting digit index + # prec = the number of total digits to compute + n += 1 # because we subtract 1 for _series + return int(math.log(n + prec)/math.log(16) + prec + 3) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..579ac3d4cd369829d7ac6c42ce86d4ba7f894646 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py @@ -0,0 +1,351 @@ +from __future__ import annotations +from sympy.core.exprtools import factor_terms +from sympy.core.numbers import Integer, Rational +from sympy.core.singleton import S +from sympy.core.symbol import Dummy +from sympy.core.sympify import _sympify +from sympy.utilities.misc import as_int + + +def continued_fraction(a) -> list: + """Return the continued fraction representation of a Rational or + quadratic irrational. + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction + >>> from sympy import sqrt + >>> continued_fraction((1 + 2*sqrt(3))/5) + [0, 1, [8, 3, 34, 3]] + + See Also + ======== + continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents + """ + e = _sympify(a) + if all(i.is_Rational for i in e.atoms()): + if e.is_Integer: + return continued_fraction_periodic(e, 1, 0) + elif e.is_Rational: + return continued_fraction_periodic(e.p, e.q, 0) + elif e.is_Pow and e.exp is S.Half and e.base.is_Integer: + return continued_fraction_periodic(0, 1, e.base) + elif e.is_Mul and len(e.args) == 2 and ( + e.args[0].is_Rational and + e.args[1].is_Pow and + e.args[1].base.is_Integer and + e.args[1].exp is S.Half): + a, b = e.args + return continued_fraction_periodic(0, a.q, b.base, a.p) + else: + # this should not have to work very hard- no + # simplification, cancel, etc... which should be + # done by the user. e.g. This is a fancy 1 but + # the user should simplify it first: + # sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2) + p, d = e.expand().as_numer_denom() + if d.is_Integer: + if p.is_Rational: + return continued_fraction_periodic(p, d) + # look for a + b*c + # with c = sqrt(s) + if p.is_Add and len(p.args) == 2: + a, bc = p.args + else: + a = S.Zero + bc = p + if a.is_Integer: + b = S.NaN + if bc.is_Mul and len(bc.args) == 2: + b, c = bc.args + elif bc.is_Pow: + b = Integer(1) + c = bc + if b.is_Integer and ( + c.is_Pow and c.exp is S.Half and + c.base.is_Integer): + # (a + b*sqrt(c))/d + c = c.base + return continued_fraction_periodic(a, d, c, b) + raise ValueError( + 'expecting a rational or quadratic irrational, not %s' % e) + + +def continued_fraction_periodic(p, q, d=0, s=1) -> list: + r""" + Find the periodic continued fraction expansion of a quadratic irrational. + + Compute the continued fraction expansion of a rational or a + quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where + `p`, `q \ne 0` and `d \ge 0` are integers. + + Returns the continued fraction representation (canonical form) as + a list of integers, optionally ending (for quadratic irrationals) + with list of integers representing the repeating digits. + + Parameters + ========== + + p : int + the rational part of the number's numerator + q : int + the denominator of the number + d : int, optional + the irrational part (discriminator) of the number's numerator + s : int, optional + the coefficient of the irrational part + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic + >>> continued_fraction_periodic(3, 2, 7) + [2, [1, 4, 1, 1]] + + Golden ratio has the simplest continued fraction expansion: + + >>> continued_fraction_periodic(1, 2, 5) + [[1]] + + If the discriminator is zero or a perfect square then the number will be a + rational number: + + >>> continued_fraction_periodic(4, 3, 0) + [1, 3] + >>> continued_fraction_periodic(4, 3, 49) + [3, 1, 2] + + See Also + ======== + + continued_fraction_iterator, continued_fraction_reduce + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction + .. [2] K. Rosen. Elementary Number theory and its applications. + Addison-Wesley, 3 Sub edition, pages 379-381, January 1992. + + """ + from sympy.functions import sqrt, floor + + p, q, d, s = list(map(as_int, [p, q, d, s])) + + if d < 0: + raise ValueError("expected non-negative for `d` but got %s" % d) + + if q == 0: + raise ValueError("The denominator cannot be 0.") + + if not s: + d = 0 + + # check for rational case + sd = sqrt(d) + if sd.is_Integer: + return list(continued_fraction_iterator(Rational(p + s*sd, q))) + + # irrational case with sd != Integer + if q < 0: + p, q, s = -p, -q, -s + + n = (p + s*sd)/q + if n < 0: + w = floor(-n) + f = -n - w + one_f = continued_fraction(1 - f) # 1-f < 1 so cf is [0 ... [...]] + one_f[0] -= w + 1 + return one_f + + d *= s**2 + sd *= s + + if (d - p**2)%q: + d *= q**2 + sd *= q + p *= q + q *= q + + terms: list[int] = [] + pq = {} + + while (p, q) not in pq: + pq[(p, q)] = len(terms) + terms.append((p + sd)//q) + p = terms[-1]*q - p + q = (d - p**2)//q + + i = pq[(p, q)] + return terms[:i] + [terms[i:]] # type: ignore + + +def continued_fraction_reduce(cf): + """ + Reduce a continued fraction to a rational or quadratic irrational. + + Compute the rational or quadratic irrational number from its + terminating or periodic continued fraction expansion. The + continued fraction expansion (cf) should be supplied as a + terminating iterator supplying the terms of the expansion. For + terminating continued fractions, this is equivalent to + ``list(continued_fraction_convergents(cf))[-1]``, only a little more + efficient. If the expansion has a repeating part, a list of the + repeating terms should be returned as the last element from the + iterator. This is the format returned by + continued_fraction_periodic. + + For quadratic irrationals, returns the largest solution found, + which is generally the one sought, if the fraction is in canonical + form (all terms positive except possibly the first). + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction_reduce + >>> continued_fraction_reduce([1, 2, 3, 4, 5]) + 225/157 + >>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2]) + -256/233 + >>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10) + 2.718281835 + >>> continued_fraction_reduce([1, 4, 2, [3, 1]]) + (sqrt(21) + 287)/238 + >>> continued_fraction_reduce([[1]]) + (1 + sqrt(5))/2 + >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic + >>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13)) + (sqrt(13) + 8)/5 + + See Also + ======== + + continued_fraction_periodic + + """ + from sympy.solvers import solve + + period = [] + x = Dummy('x') + + def untillist(cf): + for nxt in cf: + if isinstance(nxt, list): + period.extend(nxt) + yield x + break + yield nxt + + a = S.Zero + for a in continued_fraction_convergents(untillist(cf)): + pass + + if period: + y = Dummy('y') + solns = solve(continued_fraction_reduce(period + [y]) - y, y) + solns.sort() + pure = solns[-1] + rv = a.subs(x, pure).radsimp() + else: + rv = a + if rv.is_Add: + rv = factor_terms(rv) + if rv.is_Mul and rv.args[0] == -1: + rv = rv.func(*rv.args) + return rv + + +def continued_fraction_iterator(x): + """ + Return continued fraction expansion of x as iterator. + + Examples + ======== + + >>> from sympy import Rational, pi + >>> from sympy.ntheory.continued_fraction import continued_fraction_iterator + + >>> list(continued_fraction_iterator(Rational(3, 8))) + [0, 2, 1, 2] + >>> list(continued_fraction_iterator(Rational(-3, 8))) + [-1, 1, 1, 1, 2] + + >>> for i, v in enumerate(continued_fraction_iterator(pi)): + ... if i > 7: + ... break + ... print(v) + 3 + 7 + 15 + 1 + 292 + 1 + 1 + 1 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Continued_fraction + + """ + from sympy.functions import floor + while True: + i = floor(x) + yield i + x -= i + if not x: + break + x = 1/x + + +def continued_fraction_convergents(cf): + """ + Return an iterator over the convergents of a continued fraction (cf). + + The parameter should be an iterable returning successive + partial quotients of the continued fraction, such as might be + returned by continued_fraction_iterator. In computing the + convergents, the continued fraction need not be strictly in + canonical form (all integers, all but the first positive). + Rational and negative elements may be present in the expansion. + + Examples + ======== + + >>> from sympy.core import pi + >>> from sympy import S + >>> from sympy.ntheory.continued_fraction import \ + continued_fraction_convergents, continued_fraction_iterator + + >>> list(continued_fraction_convergents([0, 2, 1, 2])) + [0, 1/2, 1/3, 3/8] + + >>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')])) + [1, 3, 19/5, 7] + + >>> it = continued_fraction_convergents(continued_fraction_iterator(pi)) + >>> for n in range(7): + ... print(next(it)) + 3 + 22/7 + 333/106 + 355/113 + 103993/33102 + 104348/33215 + 208341/66317 + + See Also + ======== + + continued_fraction_iterator + + """ + p_2, q_2 = S.Zero, S.One + p_1, q_1 = S.One, S.Zero + for a in cf: + p, q = a*p_1 + p_2, a*q_1 + q_2 + p_2, q_2 = p_1, q_1 + p_1, q_1 = p, q + yield p/q diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/ecm.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/ecm.py new file mode 100644 index 0000000000000000000000000000000000000000..e854b29f5ecebdfc20c9cddf8c3e06b6ad92b247 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/ecm.py @@ -0,0 +1,326 @@ +from sympy.ntheory import sieve, isprime +from sympy.core.numbers import mod_inverse +from sympy.core.power import integer_log +from sympy.utilities.misc import as_int +import random + +rgen = random.Random() + +#----------------------------------------------------------------------------# +# # +# Lenstra's Elliptic Curve Factorization # +# # +#----------------------------------------------------------------------------# + + +class Point: + """Montgomery form of Points in an elliptic curve. + In this form, the addition and doubling of points + does not need any y-coordinate information thus + decreasing the number of operations. + Using Montgomery form we try to perform point addition + and doubling in least amount of multiplications. + + The elliptic curve used here is of the form + (E : b*y**2*z = x**3 + a*x**2*z + x*z**2). + The a_24 parameter is equal to (a + 2)/4. + + References + ========== + + .. [1] https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf + """ + + def __init__(self, x_cord, z_cord, a_24, mod): + """ + Initial parameters for the Point class. + + Parameters + ========== + + x_cord : X coordinate of the Point + z_cord : Z coordinate of the Point + a_24 : Parameter of the elliptic curve in Montgomery form + mod : modulus + """ + self.x_cord = x_cord + self.z_cord = z_cord + self.a_24 = a_24 + self.mod = mod + + def __eq__(self, other): + """Two points are equal if X/Z of both points are equal + """ + if self.a_24 != other.a_24 or self.mod != other.mod: + return False + return self.x_cord * other.z_cord % self.mod ==\ + other.x_cord * self.z_cord % self.mod + + def add(self, Q, diff): + """ + Add two points self and Q where diff = self - Q. Moreover the assumption + is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm + requires 6 multiplications. Here the difference between the points + is already known and using this algorithm speeds up the addition + by reducing the number of multiplication required. Also in the + mont_ladder algorithm is constructed in a way so that the difference + between intermediate points is always equal to the initial point. + So, we always know what the difference between the point is. + + + Parameters + ========== + + Q : point on the curve in Montgomery form + diff : self - Q + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p2 = Point(13, 10, 7, 29) + >>> p3 = p2.add(p1, p1) + >>> p3.x_cord + 23 + >>> p3.z_cord + 17 + """ + u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord) + v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord) + add, subt = u + v, u - v + x_cord = diff.z_cord * add * add % self.mod + z_cord = diff.x_cord * subt * subt % self.mod + return Point(x_cord, z_cord, self.a_24, self.mod) + + def double(self): + """ + Doubles a point in an elliptic curve in Montgomery form. + This algorithm requires 5 multiplications. + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p2 = p1.double() + >>> p2.x_cord + 13 + >>> p2.z_cord + 10 + """ + u = pow(self.x_cord + self.z_cord, 2, self.mod) + v = pow(self.x_cord - self.z_cord, 2, self.mod) + diff = u - v + x_cord = u*v % self.mod + z_cord = diff*(v + self.a_24*diff) % self.mod + return Point(x_cord, z_cord, self.a_24, self.mod) + + def mont_ladder(self, k): + """ + Scalar multiplication of a point in Montgomery form + using Montgomery Ladder Algorithm. + A total of 11 multiplications are required in each step of this + algorithm. + + Parameters + ========== + + k : The positive integer multiplier + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p3 = p1.mont_ladder(3) + >>> p3.x_cord + 23 + >>> p3.z_cord + 17 + """ + Q = self + R = self.double() + for i in bin(k)[3:]: + if i == '1': + Q = R.add(Q, self) + R = R.double() + else: + R = Q.add(R, self) + Q = Q.double() + return Q + + +def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): + """Returns one factor of n using + Lenstra's 2 Stage Elliptic curve Factorization + with Suyama's Parameterization. Here Montgomery + arithmetic is used for fast computation of addition + and doubling of points in elliptic curve. + + This ECM method considers elliptic curves in Montgomery + form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves + elliptic curve operations (mod N), where the elements in + Z are reduced (mod N). Since N is not a prime, E over FF(N) + is not really an elliptic curve but we can still do point additions + and doubling as if FF(N) was a field. + + Stage 1 : The basic algorithm involves taking a random point (P) on an + elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. + Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, + might be a smooth number that divides k. Then we have k = l * |E(FF(q))| + for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, + hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn + factor of N (q) can be recovered by taking gcd(kP.z_cord, N). + + Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize + the fact that even if kP != 0, the value of k might miss just one large + prime divisor of |E(FF(q))|. In this case we only need to compute the + scalar multiplication by p to get p*k*P = O. Here a second bound B2 + restrict the size of possible values of p. + + Parameters + ========== + + n : Number to be Factored + B1 : Stage 1 Bound + B2 : Stage 2 Bound + max_curve : Maximum number of curves generated + + References + ========== + + .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: + A Computational Perspective" (2nd Ed.), page 344 + """ + n = as_int(n) + if B1 % 2 != 0 or B2 % 2 != 0: + raise ValueError("The Bounds should be an even integer") + sieve.extend(B2) + + if isprime(n): + return n + + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.polys.polytools import gcd + D = int(sqrt(B2)) + beta = [0]*(D + 1) + S = [0]*(D + 1) + k = 1 + for p in sieve.primerange(1, B1 + 1): + k *= pow(p, integer_log(B1, p)[0]) + for _ in range(max_curve): + #Suyama's Parametrization + sigma = rgen.randint(6, n - 1) + u = (sigma*sigma - 5) % n + v = (4*sigma) % n + u_3 = pow(u, 3, n) + + try: + # We use the elliptic curve y**2 = x**3 + a*x**2 + x + # where a = pow(v - u, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2 + # However, we do not declare a because it is more convenient + # to use a24 = (a + 2)*mod_inverse(4, n) in the calculation. + a24 = pow(v - u, 3, n)*(3*u + v)*mod_inverse(16*u_3*v, n) % n + except ValueError: + #If the mod_inverse(16*u_3*v, n) doesn't exist (i.e., g != 1) + g = gcd(16*u_3*v, n) + #If g = n, try another curve + if g == n: + continue + return g + + Q = Point(u_3, pow(v, 3, n), a24, n) + Q = Q.mont_ladder(k) + g = gcd(Q.z_cord, n) + + #Stage 1 factor + if g != 1 and g != n: + return g + #Stage 1 failure. Q.z = 0, Try another curve + elif g == n: + continue + + #Stage 2 - Improved Standard Continuation + S[1] = Q.double() + S[2] = S[1].double() + beta[1] = (S[1].x_cord*S[1].z_cord) % n + beta[2] = (S[2].x_cord*S[2].z_cord) % n + + for d in range(3, D + 1): + S[d] = S[d - 1].add(S[1], S[d - 2]) + beta[d] = (S[d].x_cord*S[d].z_cord) % n + + g = 1 + B = B1 - 1 + T = Q.mont_ladder(B - 2*D) + R = Q.mont_ladder(B) + + for r in range(B, B2, 2*D): + alpha = (R.x_cord*R.z_cord) % n + for q in sieve.primerange(r + 2, r + 2*D + 1): + delta = (q - r) // 2 + # We want to calculate + # f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord + f = (R.x_cord - S[delta].x_cord)*\ + (R.z_cord + S[delta].z_cord) - alpha + beta[delta] + g = (g*f) % n + #Swap + T, R = R, R.add(S[D], T) + g = gcd(n, g) + + #Stage 2 Factor found + if g != 1 and g != n: + return g + + #ECM failed, Increase the bounds + raise ValueError("Increase the bounds") + + +def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234): + """Performs factorization using Lenstra's Elliptic curve method. + + This function repeatedly calls `ecm_one_factor` to compute the factors + of n. First all the small factors are taken out using trial division. + Then `ecm_one_factor` is used to compute one factor at a time. + + Parameters + ========== + + n : Number to be Factored + B1 : Stage 1 Bound + B2 : Stage 2 Bound + max_curve : Maximum number of curves generated + seed : Initialize pseudorandom generator + + Examples + ======== + + >>> from sympy.ntheory import ecm + >>> ecm(25645121643901801) + {5394769, 4753701529} + >>> ecm(9804659461513846513) + {4641991, 2112166839943} + """ + _factors = set() + for prime in sieve.primerange(1, 100000): + if n % prime == 0: + _factors.add(prime) + while(n % prime == 0): + n //= prime + rgen.seed(seed) + while(n > 1): + try: + factor = _ecm_one_factor(n, B1, B2, max_curve) + except ValueError: + raise ValueError("Increase the bounds") + _factors.add(factor) + n //= factor + + factors = set() + for factor in _factors: + if isprime(factor): + factors.add(factor) + continue + factors |= ecm(factor) + return factors diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..8a42540b372042f596808684fef8e3fc57935b74 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py @@ -0,0 +1,223 @@ +from sympy.core.containers import Tuple +from sympy.core.numbers import (Integer, Rational) +from sympy.core.singleton import S +import sympy.polys + +from math import gcd + + +def egyptian_fraction(r, algorithm="Greedy"): + """ + Return the list of denominators of an Egyptian fraction + expansion [1]_ of the said rational `r`. + + Parameters + ========== + + r : Rational or (p, q) + a positive rational number, ``p/q``. + algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional + Denotes the algorithm to be used (the default is "Greedy"). + + Examples + ======== + + >>> from sympy import Rational + >>> from sympy.ntheory.egyptian_fraction import egyptian_fraction + >>> egyptian_fraction(Rational(3, 7)) + [3, 11, 231] + >>> egyptian_fraction((3, 7), "Graham Jewett") + [7, 8, 9, 56, 57, 72, 3192] + >>> egyptian_fraction((3, 7), "Takenouchi") + [4, 7, 28] + >>> egyptian_fraction((3, 7), "Golomb") + [3, 15, 35] + >>> egyptian_fraction((11, 5), "Golomb") + [1, 2, 3, 4, 9, 234, 1118, 2580] + + See Also + ======== + + sympy.core.numbers.Rational + + Notes + ===== + + Currently the following algorithms are supported: + + 1) Greedy Algorithm + + Also called the Fibonacci-Sylvester algorithm [2]_. + At each step, extract the largest unit fraction less + than the target and replace the target with the remainder. + + It has some distinct properties: + + a) Given `p/q` in lowest terms, generates an expansion of maximum + length `p`. Even as the numerators get large, the number of + terms is seldom more than a handful. + + b) Uses minimal memory. + + c) The terms can blow up (standard examples of this are 5/121 and + 31/311). The denominator is at most squared at each step + (doubly-exponential growth) and typically exhibits + singly-exponential growth. + + 2) Graham Jewett Algorithm + + The algorithm suggested by the result of Graham and Jewett. + Note that this has a tendency to blow up: the length of the + resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_. + + 3) Takenouchi Algorithm + + The algorithm suggested by Takenouchi (1921). + Differs from the Graham-Jewett algorithm only in the handling + of duplicates. See [3]_. + + 4) Golomb's Algorithm + + A method given by Golumb (1962), using modular arithmetic and + inverses. It yields the same results as a method using continued + fractions proposed by Bleicher (1972). See [4]_. + + If the given rational is greater than or equal to 1, a greedy algorithm + of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking + all the unit fractions of this sequence until adding one more would be + greater than the given number. This list of denominators is prefixed + to the result from the requested algorithm used on the remainder. For + example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4, + 5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5, + 6, 7] is part of the harmonic sequence summing to 363/140, leaving a + remainder of 31/420, which yields [14, 420] by the Greedy algorithm. + The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3, + 4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Egyptian_fraction + .. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions + .. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html + .. [4] https://web.archive.org/web/20180413004012/https://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf + + """ + + if not isinstance(r, Rational): + if isinstance(r, (Tuple, tuple)) and len(r) == 2: + r = Rational(*r) + else: + raise ValueError("Value must be a Rational or tuple of ints") + if r <= 0: + raise ValueError("Value must be positive") + + # common cases that all methods agree on + x, y = r.as_numer_denom() + if y == 1 and x == 2: + return [Integer(i) for i in [1, 2, 3, 6]] + if x == y + 1: + return [S.One, y] + + prefix, rem = egypt_harmonic(r) + if rem == 0: + return prefix + # work in Python ints + x, y = rem.p, rem.q + # assert x < y and gcd(x, y) = 1 + + if algorithm == "Greedy": + postfix = egypt_greedy(x, y) + elif algorithm == "Graham Jewett": + postfix = egypt_graham_jewett(x, y) + elif algorithm == "Takenouchi": + postfix = egypt_takenouchi(x, y) + elif algorithm == "Golomb": + postfix = egypt_golomb(x, y) + else: + raise ValueError("Entered invalid algorithm") + return prefix + [Integer(i) for i in postfix] + + +def egypt_greedy(x, y): + # assumes gcd(x, y) == 1 + if x == 1: + return [y] + else: + a = (-y) % x + b = y*(y//x + 1) + c = gcd(a, b) + if c > 1: + num, denom = a//c, b//c + else: + num, denom = a, b + return [y//x + 1] + egypt_greedy(num, denom) + + +def egypt_graham_jewett(x, y): + # assumes gcd(x, y) == 1 + l = [y] * x + + # l is now a list of integers whose reciprocals sum to x/y. + # we shall now proceed to manipulate the elements of l without + # changing the reciprocated sum until all elements are unique. + + while len(l) != len(set(l)): + l.sort() # so the list has duplicates. find a smallest pair + for i in range(len(l) - 1): + if l[i] == l[i + 1]: + break + # we have now identified a pair of identical + # elements: l[i] and l[i + 1]. + # now comes the application of the result of graham and jewett: + l[i + 1] = l[i] + 1 + # and we just iterate that until the list has no duplicates. + l.append(l[i]*(l[i] + 1)) + return sorted(l) + + +def egypt_takenouchi(x, y): + # assumes gcd(x, y) == 1 + # special cases for 3/y + if x == 3: + if y % 2 == 0: + return [y//2, y] + i = (y - 1)//2 + j = i + 1 + k = j + i + return [j, k, j*k] + l = [y] * x + while len(l) != len(set(l)): + l.sort() + for i in range(len(l) - 1): + if l[i] == l[i + 1]: + break + k = l[i] + if k % 2 == 0: + l[i] = l[i] // 2 + del l[i + 1] + else: + l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2 + return sorted(l) + + +def egypt_golomb(x, y): + # assumes x < y and gcd(x, y) == 1 + if x == 1: + return [y] + xp = sympy.polys.ZZ.invert(int(x), int(y)) + rv = [xp*y] + rv.extend(egypt_golomb((x*xp - 1)//y, xp)) + return sorted(rv) + + +def egypt_harmonic(r): + # assumes r is Rational + rv = [] + d = S.One + acc = S.Zero + while acc + 1/d <= r: + acc += 1/d + rv.append(d) + d += 1 + return (rv, r - acc) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/factor_.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/factor_.py new file mode 100644 index 0000000000000000000000000000000000000000..67e1242dcced325578e0d7469b585ff41a1c2ed6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/factor_.py @@ -0,0 +1,2654 @@ +""" +Integer factorization +""" + +from collections import defaultdict +from functools import reduce +import random +import math + +from sympy.core import sympify +from sympy.core.containers import Dict +from sympy.core.evalf import bitcount +from sympy.core.expr import Expr +from sympy.core.function import Function +from sympy.core.logic import fuzzy_and +from sympy.core.mul import Mul +from sympy.core.numbers import igcd, ilcm, Rational, Integer +from sympy.core.power import integer_nthroot, Pow, integer_log +from sympy.core.singleton import S +from sympy.external.gmpy import SYMPY_INTS +from .primetest import isprime +from .generate import sieve, primerange, nextprime +from .digits import digits +from sympy.utilities.iterables import flatten +from sympy.utilities.misc import as_int, filldedent +from .ecm import _ecm_one_factor + +# Note: This list should be updated whenever new Mersenne primes are found. +# Refer: https://www.mersenne.org/ +MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, + 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, + 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, + 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933) + +# compute more when needed for i in Mersenne prime exponents +PERFECT = [6] # 2**(i-1)*(2**i-1) +MERSENNES = [3] # 2**i - 1 + + +def _ismersenneprime(n): + global MERSENNES + j = len(MERSENNES) + while n > MERSENNES[-1] and j < len(MERSENNE_PRIME_EXPONENTS): + # conservatively grow the list + MERSENNES.append(2**MERSENNE_PRIME_EXPONENTS[j] - 1) + j += 1 + return n in MERSENNES + + +def _isperfect(n): + global PERFECT + if n % 2 == 0: + j = len(PERFECT) + while n > PERFECT[-1] and j < len(MERSENNE_PRIME_EXPONENTS): + # conservatively grow the list + t = 2**(MERSENNE_PRIME_EXPONENTS[j] - 1) + PERFECT.append(t*(2*t - 1)) + j += 1 + return n in PERFECT + + +small_trailing = [0] * 256 +for j in range(1,8): + small_trailing[1<>> from sympy.ntheory.factor_ import smoothness + >>> smoothness(2**7*3**2) + (3, 128) + >>> smoothness(2**4*13) + (13, 16) + >>> smoothness(2) + (2, 2) + + See Also + ======== + + factorint, smoothness_p + """ + + if n == 1: + return (1, 1) # not prime, but otherwise this causes headaches + facs = factorint(n) + return max(facs), max(m**facs[m] for m in facs) + + +def smoothness_p(n, m=-1, power=0, visual=None): + """ + Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...] + where: + + 1. p**M is the base-p divisor of n + 2. sm(p + m) is the smoothness of p + m (m = -1 by default) + 3. psm(p + m) is the power smoothness of p + m + + The list is sorted according to smoothness (default) or by power smoothness + if power=1. + + The smoothness of the numbers to the left (m = -1) or right (m = 1) of a + factor govern the results that are obtained from the p +/- 1 type factoring + methods. + + >>> from sympy.ntheory.factor_ import smoothness_p, factorint + >>> smoothness_p(10431, m=1) + (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) + >>> smoothness_p(10431) + (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) + >>> smoothness_p(10431, power=1) + (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) + + If visual=True then an annotated string will be returned: + + >>> print(smoothness_p(21477639576571, visual=1)) + p**i=4410317**1 has p-1 B=1787, B-pow=1787 + p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 + + This string can also be generated directly from a factorization dictionary + and vice versa: + + >>> factorint(17*9) + {3: 2, 17: 1} + >>> smoothness_p(_) + 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16' + >>> smoothness_p(_) + {3: 2, 17: 1} + + The table of the output logic is: + + ====== ====== ======= ======= + | Visual + ------ ---------------------- + Input True False other + ====== ====== ======= ======= + dict str tuple str + str str tuple dict + tuple str tuple str + n str tuple tuple + mul str tuple tuple + ====== ====== ======= ======= + + See Also + ======== + + factorint, smoothness + """ + + # visual must be True, False or other (stored as None) + if visual in (1, 0): + visual = bool(visual) + elif visual not in (True, False): + visual = None + + if isinstance(n, str): + if visual: + return n + d = {} + for li in n.splitlines(): + k, v = [int(i) for i in + li.split('has')[0].split('=')[1].split('**')] + d[k] = v + if visual is not True and visual is not False: + return d + return smoothness_p(d, visual=False) + elif not isinstance(n, tuple): + facs = factorint(n, visual=False) + + if power: + k = -1 + else: + k = 1 + if isinstance(n, tuple): + rv = n + else: + rv = (m, sorted([(f, + tuple([M] + list(smoothness(f + m)))) + for f, M in list(facs.items())], + key=lambda x: (x[1][k], x[0]))) + + if visual is False or (visual is not True) and (type(n) in [int, Mul]): + return rv + lines = [] + for dat in rv[1]: + dat = flatten(dat) + dat.insert(2, m) + lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat)) + return '\n'.join(lines) + + +def trailing(n): + """Count the number of trailing zero digits in the binary + representation of n, i.e. determine the largest power of 2 + that divides n. + + Examples + ======== + + >>> from sympy import trailing + >>> trailing(128) + 7 + >>> trailing(63) + 0 + """ + n = abs(int(n)) + if not n: + return 0 + low_byte = n & 0xff + if low_byte: + return small_trailing[low_byte] + + # 2**m is quick for z up through 2**30 + z = bitcount(n) - 1 + if isinstance(z, SYMPY_INTS): + if n == 1 << z: + return z + + if z < 300: + # fixed 8-byte reduction + t = 8 + n >>= 8 + while not n & 0xff: + n >>= 8 + t += 8 + return t + small_trailing[n & 0xff] + + # binary reduction important when there might be a large + # number of trailing 0s + t = 0 + p = 8 + while not n & 1: + while not n & ((1 << p) - 1): + n >>= p + t += p + p *= 2 + p //= 2 + return t + + +def multiplicity(p, n): + """ + Find the greatest integer m such that p**m divides n. + + Examples + ======== + + >>> from sympy import multiplicity, Rational + >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]] + [0, 1, 2, 3, 3] + >>> multiplicity(3, Rational(1, 9)) + -2 + + Note: when checking for the multiplicity of a number in a + large factorial it is most efficient to send it as an unevaluated + factorial or to call ``multiplicity_in_factorial`` directly: + + >>> from sympy.ntheory import multiplicity_in_factorial + >>> from sympy import factorial + >>> p = factorial(25) + >>> n = 2**100 + >>> nfac = factorial(n, evaluate=False) + >>> multiplicity(p, nfac) + 52818775009509558395695966887 + >>> _ == multiplicity_in_factorial(p, n) + True + + """ + try: + p, n = as_int(p), as_int(n) + except ValueError: + from sympy.functions.combinatorial.factorials import factorial + if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)): + p = Rational(p) + n = Rational(n) + if p.q == 1: + if n.p == 1: + return -multiplicity(p.p, n.q) + return multiplicity(p.p, n.p) - multiplicity(p.p, n.q) + elif p.p == 1: + return multiplicity(p.q, n.q) + else: + like = min( + multiplicity(p.p, n.p), + multiplicity(p.q, n.q)) + cross = min( + multiplicity(p.q, n.p), + multiplicity(p.p, n.q)) + return like - cross + elif (isinstance(p, (SYMPY_INTS, Integer)) and + isinstance(n, factorial) and + isinstance(n.args[0], Integer) and + n.args[0] >= 0): + return multiplicity_in_factorial(p, n.args[0]) + raise ValueError('expecting ints or fractions, got %s and %s' % (p, n)) + + if n == 0: + raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n)) + if p == 2: + return trailing(n) + if p < 2: + raise ValueError('p must be an integer, 2 or larger, but got %s' % p) + if p == n: + return 1 + + m = 0 + n, rem = divmod(n, p) + while not rem: + m += 1 + if m > 5: + # The multiplicity could be very large. Better + # to increment in powers of two + e = 2 + while 1: + ppow = p**e + if ppow < n: + nnew, rem = divmod(n, ppow) + if not rem: + m += e + e *= 2 + n = nnew + continue + return m + multiplicity(p, n) + n, rem = divmod(n, p) + return m + + +def multiplicity_in_factorial(p, n): + """return the largest integer ``m`` such that ``p**m`` divides ``n!`` + without calculating the factorial of ``n``. + + + Examples + ======== + + >>> from sympy.ntheory import multiplicity_in_factorial + >>> from sympy import factorial + + >>> multiplicity_in_factorial(2, 3) + 1 + + An instructive use of this is to tell how many trailing zeros + a given factorial has. For example, there are 6 in 25!: + + >>> factorial(25) + 15511210043330985984000000 + >>> multiplicity_in_factorial(10, 25) + 6 + + For large factorials, it is much faster/feasible to use + this function rather than computing the actual factorial: + + >>> multiplicity_in_factorial(factorial(25), 2**100) + 52818775009509558395695966887 + + """ + + p, n = as_int(p), as_int(n) + + if p <= 0: + raise ValueError('expecting positive integer got %s' % p ) + + if n < 0: + raise ValueError('expecting non-negative integer got %s' % n ) + + factors = factorint(p) + + # keep only the largest of a given multiplicity since those + # of a given multiplicity will be goverened by the behavior + # of the largest factor + test = defaultdict(int) + for k, v in factors.items(): + test[v] = max(k, test[v]) + keep = set(test.values()) + # remove others from factors + for k in list(factors.keys()): + if k not in keep: + factors.pop(k) + + mp = S.Infinity + for i in factors: + # multiplicity of i in n! is + mi = (n - (sum(digits(n, i)) - i))//(i - 1) + # multiplicity of p in n! depends on multiplicity + # of prime `i` in p, so we floor divide by factors[i] + # and keep it if smaller than the multiplicity of p + # seen so far + mp = min(mp, mi//factors[i]) + + return mp + + +def perfect_power(n, candidates=None, big=True, factor=True): + """ + Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique + perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a + perfect power). A ValueError is raised if ``n`` is not Rational. + + By default, the base is recursively decomposed and the exponents + collected so the largest possible ``e`` is sought. If ``big=False`` + then the smallest possible ``e`` (thus prime) will be chosen. + + If ``factor=True`` then simultaneous factorization of ``n`` is + attempted since finding a factor indicates the only possible root + for ``n``. This is True by default since only a few small factors will + be tested in the course of searching for the perfect power. + + The use of ``candidates`` is primarily for internal use; if provided, + False will be returned if ``n`` cannot be written as a power with one + of the candidates as an exponent and factoring (beyond testing for + a factor of 2) will not be attempted. + + Examples + ======== + + >>> from sympy import perfect_power, Rational + >>> perfect_power(16) + (2, 4) + >>> perfect_power(16, big=False) + (4, 2) + + Negative numbers can only have odd perfect powers: + + >>> perfect_power(-4) + False + >>> perfect_power(-8) + (-2, 3) + + Rationals are also recognized: + + >>> perfect_power(Rational(1, 2)**3) + (1/2, 3) + >>> perfect_power(Rational(-3, 2)**3) + (-3/2, 3) + + Notes + ===== + + To know whether an integer is a perfect power of 2 use + + >>> is2pow = lambda n: bool(n and not n & (n - 1)) + >>> [(i, is2pow(i)) for i in range(5)] + [(0, False), (1, True), (2, True), (3, False), (4, True)] + + It is not necessary to provide ``candidates``. When provided + it will be assumed that they are ints. The first one that is + larger than the computed maximum possible exponent will signal + failure for the routine. + + >>> perfect_power(3**8, [9]) + False + >>> perfect_power(3**8, [2, 4, 8]) + (3, 8) + >>> perfect_power(3**8, [4, 8], big=False) + (9, 4) + + See Also + ======== + sympy.core.power.integer_nthroot + sympy.ntheory.primetest.is_square + """ + if isinstance(n, Rational) and not n.is_Integer: + p, q = n.as_numer_denom() + if p is S.One: + pp = perfect_power(q) + if pp: + pp = (n.func(1, pp[0]), pp[1]) + else: + pp = perfect_power(p) + if pp: + num, e = pp + pq = perfect_power(q, [e]) + if pq: + den, _ = pq + pp = n.func(num, den), e + return pp + + n = as_int(n) + if n < 0: + pp = perfect_power(-n) + if pp: + b, e = pp + if e % 2: + return -b, e + return False + + if n <= 3: + # no unique exponent for 0, 1 + # 2 and 3 have exponents of 1 + return False + logn = math.log(n, 2) + max_possible = int(logn) + 2 # only check values less than this + not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8 + min_possible = 2 + not_square + if not candidates: + candidates = primerange(min_possible, max_possible) + else: + candidates = sorted([i for i in candidates + if min_possible <= i < max_possible]) + if n%2 == 0: + e = trailing(n) + candidates = [i for i in candidates if e%i == 0] + if big: + candidates = reversed(candidates) + for e in candidates: + r, ok = integer_nthroot(n, e) + if ok: + return (r, e) + return False + + def _factors(): + rv = 2 + n % 2 + while True: + yield rv + rv = nextprime(rv) + + for fac, e in zip(_factors(), candidates): + # see if there is a factor present + if factor and n % fac == 0: + # find what the potential power is + if fac == 2: + e = trailing(n) + else: + e = multiplicity(fac, n) + # if it's a trivial power we are done + if e == 1: + return False + + # maybe the e-th root of n is exact + r, exact = integer_nthroot(n, e) + if not exact: + # Having a factor, we know that e is the maximal + # possible value for a root of n. + # If n = fac**e*m can be written as a perfect + # power then see if m can be written as r**E where + # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E + m = n//fac**e + rE = perfect_power(m, candidates=divisors(e, generator=True)) + if not rE: + return False + else: + r, E = rE + r, e = fac**(e//E)*r, E + if not big: + e0 = primefactors(e) + if e0[0] != e: + r, e = r**(e//e0[0]), e0[0] + return r, e + + # Weed out downright impossible candidates + if logn/e < 40: + b = 2.0**(logn/e) + if abs(int(b + 0.5) - b) > 0.01: + continue + + # now see if the plausible e makes a perfect power + r, exact = integer_nthroot(n, e) + if exact: + if big: + m = perfect_power(r, big=big, factor=factor) + if m: + r, e = m[0], e*m[1] + return int(r), e + + return False + + +def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None): + r""" + Use Pollard's rho method to try to extract a nontrivial factor + of ``n``. The returned factor may be a composite number. If no + factor is found, ``None`` is returned. + + The algorithm generates pseudo-random values of x with a generator + function, replacing x with F(x). If F is not supplied then the + function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``. + Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be + supplied; the ``a`` will be ignored if F was supplied. + + The sequence of numbers generated by such functions generally have a + a lead-up to some number and then loop around back to that number and + begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader + and loop look a bit like the Greek letter rho, and thus the name, 'rho'. + + For a given function, very different leader-loop values can be obtained + so it is a good idea to allow for retries: + + >>> from sympy.ntheory.generate import cycle_length + >>> n = 16843009 + >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n + >>> for s in range(5): + ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s))) + ... + loop length = 2489; leader length = 42 + loop length = 78; leader length = 120 + loop length = 1482; leader length = 99 + loop length = 1482; leader length = 285 + loop length = 1482; leader length = 100 + + Here is an explicit example where there is a two element leadup to + a sequence of 3 numbers (11, 14, 4) that then repeat: + + >>> x=2 + >>> for i in range(9): + ... x=(x**2+12)%17 + ... print(x) + ... + 16 + 13 + 11 + 14 + 4 + 11 + 14 + 4 + 11 + >>> next(cycle_length(lambda x: (x**2+12)%17, 2)) + (3, 2) + >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True)) + [16, 13, 11, 14, 4] + + Instead of checking the differences of all generated values for a gcd + with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd, + 2nd and 4th, 3rd and 6th until it has been detected that the loop has been + traversed. Loops may be many thousands of steps long before rho finds a + factor or reports failure. If ``max_steps`` is specified, the iteration + is cancelled with a failure after the specified number of steps. + + Examples + ======== + + >>> from sympy import pollard_rho + >>> n=16843009 + >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n + >>> pollard_rho(n, F=F) + 257 + + Use the default setting with a bad value of ``a`` and no retries: + + >>> pollard_rho(n, a=n-2, retries=0) + + If retries is > 0 then perhaps the problem will correct itself when + new values are generated for a: + + >>> pollard_rho(n, a=n-2, retries=1) + 257 + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 229-231 + + """ + n = int(n) + if n < 5: + raise ValueError('pollard_rho should receive n > 4') + prng = random.Random(seed + retries) + V = s + for i in range(retries + 1): + U = V + if not F: + F = lambda x: (pow(x, 2, n) + a) % n + j = 0 + while 1: + if max_steps and (j > max_steps): + break + j += 1 + U = F(U) + V = F(F(V)) # V is 2x further along than U + g = igcd(U - V, n) + if g == 1: + continue + if g == n: + break + return int(g) + V = prng.randint(0, n - 1) + a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2 + F = None + return None + + +def pollard_pm1(n, B=10, a=2, retries=0, seed=1234): + """ + Use Pollard's p-1 method to try to extract a nontrivial factor + of ``n``. Either a divisor (perhaps composite) or ``None`` is returned. + + The value of ``a`` is the base that is used in the test gcd(a**M - 1, n). + The default is 2. If ``retries`` > 0 then if no factor is found after the + first attempt, a new ``a`` will be generated randomly (using the ``seed``) + and the process repeated. + + Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)). + + A search is made for factors next to even numbers having a power smoothness + less than ``B``. Choosing a larger B increases the likelihood of finding a + larger factor but takes longer. Whether a factor of n is found or not + depends on ``a`` and the power smoothness of the even number just less than + the factor p (hence the name p - 1). + + Although some discussion of what constitutes a good ``a`` some + descriptions are hard to interpret. At the modular.math site referenced + below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1 + for every prime power divisor of N. But consider the following: + + >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1 + >>> n=257*1009 + >>> smoothness_p(n) + (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))]) + + So we should (and can) find a root with B=16: + + >>> pollard_pm1(n, B=16, a=3) + 1009 + + If we attempt to increase B to 256 we find that it does not work: + + >>> pollard_pm1(n, B=256) + >>> + + But if the value of ``a`` is changed we find that only multiples of + 257 work, e.g.: + + >>> pollard_pm1(n, B=256, a=257) + 1009 + + Checking different ``a`` values shows that all the ones that did not + work had a gcd value not equal to ``n`` but equal to one of the + factors: + + >>> from sympy import ilcm, igcd, factorint, Pow + >>> M = 1 + >>> for i in range(2, 256): + ... M = ilcm(M, i) + ... + >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if + ... igcd(pow(a, M, n) - 1, n) != n]) + {1009} + + But does aM % d for every divisor of n give 1? + + >>> aM = pow(255, M, n) + >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args] + [(257**1, 1), (1009**1, 1)] + + No, only one of them. So perhaps the principle is that a root will + be found for a given value of B provided that: + + 1) the power smoothness of the p - 1 value next to the root + does not exceed B + 2) a**M % p != 1 for any of the divisors of n. + + By trying more than one ``a`` it is possible that one of them + will yield a factor. + + Examples + ======== + + With the default smoothness bound, this number cannot be cracked: + + >>> from sympy.ntheory import pollard_pm1 + >>> pollard_pm1(21477639576571) + + Increasing the smoothness bound helps: + + >>> pollard_pm1(21477639576571, B=2000) + 4410317 + + Looking at the smoothness of the factors of this number we find: + + >>> from sympy.ntheory.factor_ import smoothness_p, factorint + >>> print(smoothness_p(21477639576571, visual=1)) + p**i=4410317**1 has p-1 B=1787, B-pow=1787 + p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 + + The B and B-pow are the same for the p - 1 factorizations of the divisors + because those factorizations had a very large prime factor: + + >>> factorint(4410317 - 1) + {2: 2, 617: 1, 1787: 1} + >>> factorint(4869863-1) + {2: 1, 2434931: 1} + + Note that until B reaches the B-pow value of 1787, the number is not cracked; + + >>> pollard_pm1(21477639576571, B=1786) + >>> pollard_pm1(21477639576571, B=1787) + 4410317 + + The B value has to do with the factors of the number next to the divisor, + not the divisors themselves. A worst case scenario is that the number next + to the factor p has a large prime divisisor or is a perfect power. If these + conditions apply then the power-smoothness will be about p/2 or p. The more + realistic is that there will be a large prime factor next to p requiring + a B value on the order of p/2. Although primes may have been searched for + up to this level, the p/2 is a factor of p - 1, something that we do not + know. The modular.math reference below states that 15% of numbers in the + range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6 + will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the + percentages are nearly reversed...but in that range the simple trial + division is quite fast. + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 236-238 + .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html + .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf + """ + + n = int(n) + if n < 4 or B < 3: + raise ValueError('pollard_pm1 should receive n > 3 and B > 2') + prng = random.Random(seed + B) + + # computing a**lcm(1,2,3,..B) % n for B > 2 + # it looks weird, but it's right: primes run [2, B] + # and the answer's not right until the loop is done. + for i in range(retries + 1): + aM = a + for p in sieve.primerange(2, B + 1): + e = int(math.log(B, p)) + aM = pow(aM, pow(p, e), n) + g = igcd(aM - 1, n) + if 1 < g < n: + return int(g) + + # get a new a: + # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1' + # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will + # give a zero, too, so we set the range as [2, n-2]. Some references + # say 'a' should be coprime to n, but either will detect factors. + a = prng.randint(2, n - 2) + + +def _trial(factors, n, candidates, verbose=False): + """ + Helper function for integer factorization. Trial factors ``n` + against all integers given in the sequence ``candidates`` + and updates the dict ``factors`` in-place. Returns the reduced + value of ``n`` and a flag indicating whether any factors were found. + """ + if verbose: + factors0 = list(factors.keys()) + nfactors = len(factors) + for d in candidates: + if n % d == 0: + m = multiplicity(d, n) + n //= d**m + factors[d] = m + if verbose: + for k in sorted(set(factors).difference(set(factors0))): + print(factor_msg % (k, factors[k])) + return int(n), len(factors) != nfactors + + +def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1, + verbose): + """ + Helper function for integer factorization. Checks if ``n`` + is a prime or a perfect power, and in those cases updates + the factorization and raises ``StopIteration``. + """ + + if verbose: + print('Check for termination') + + # since we've already been factoring there is no need to do + # simultaneous factoring with the power check + p = perfect_power(n, factor=False) + if p is not False: + base, exp = p + if limitp1: + limit = limitp1 - 1 + else: + limit = limitp1 + facs = factorint(base, limit, use_trial, use_rho, use_pm1, + verbose=False) + for b, e in facs.items(): + if verbose: + print(factor_msg % (b, e)) + factors[b] = exp*e + raise StopIteration + + if isprime(n): + factors[int(n)] = 1 + raise StopIteration + + if n == 1: + raise StopIteration + +trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i" +trial_msg = "Trial division with primes [%i ... %i]" +rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i" +pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i" +ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i" +factor_msg = '\t%i ** %i' +fermat_msg = 'Close factors satisying Fermat condition found.' +complete_msg = 'Factorization is complete.' + + +def _factorint_small(factors, n, limit, fail_max): + """ + Return the value of n and either a 0 (indicating that factorization up + to the limit was complete) or else the next near-prime that would have + been tested. + + Factoring stops if there are fail_max unsuccessful tests in a row. + + If factors of n were found they will be in the factors dictionary as + {factor: multiplicity} and the returned value of n will have had those + factors removed. The factors dictionary is modified in-place. + + """ + + def done(n, d): + """return n, d if the sqrt(n) was not reached yet, else + n, 0 indicating that factoring is done. + """ + if d*d <= n: + return n, d + return n, 0 + + d = 2 + m = trailing(n) + if m: + factors[d] = m + n >>= m + d = 3 + if limit < d: + if n > 1: + factors[n] = 1 + return done(n, d) + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + + # when d*d exceeds maxx or n we are done; if limit**2 is greater + # than n then maxx is set to zero so the value of n will flag the finish + if limit*limit > n: + maxx = 0 + else: + maxx = limit*limit + + dd = maxx or n + d = 5 + fails = 0 + while fails < fail_max: + if d*d > dd: + break + # d = 6*i - 1 + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + dd = maxx or n + fails = 0 + else: + fails += 1 + d += 2 + if d*d > dd: + break + # d = 6*i - 1 + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + dd = maxx or n + fails = 0 + else: + fails += 1 + # d = 6*(i + 1) - 1 + d += 4 + + return done(n, d) + + +def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, + use_ecm=True, verbose=False, visual=None, multiple=False): + r""" + Given a positive integer ``n``, ``factorint(n)`` returns a dict containing + the prime factors of ``n`` as keys and their respective multiplicities + as values. For example: + + >>> from sympy.ntheory import factorint + >>> factorint(2000) # 2000 = (2**4) * (5**3) + {2: 4, 5: 3} + >>> factorint(65537) # This number is prime + {65537: 1} + + For input less than 2, factorint behaves as follows: + + - ``factorint(1)`` returns the empty factorization, ``{}`` + - ``factorint(0)`` returns ``{0:1}`` + - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n`` + + Partial Factorization: + + If ``limit`` (> 3) is specified, the search is stopped after performing + trial division up to (and including) the limit (or taking a + corresponding number of rho/p-1 steps). This is useful if one has + a large number and only is interested in finding small factors (if + any). Note that setting a limit does not prevent larger factors + from being found early; it simply means that the largest factor may + be composite. Since checking for perfect power is relatively cheap, it is + done regardless of the limit setting. + + This number, for example, has two small factors and a huge + semi-prime factor that cannot be reduced easily: + + >>> from sympy.ntheory import isprime + >>> a = 1407633717262338957430697921446883 + >>> f = factorint(a, limit=10000) + >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1} + True + >>> isprime(max(f)) + False + + This number has a small factor and a residual perfect power whose + base is greater than the limit: + + >>> factorint(3*101**7, limit=5) + {3: 1, 101: 7} + + List of Factors: + + If ``multiple`` is set to ``True`` then a list containing the + prime factors including multiplicities is returned. + + >>> factorint(24, multiple=True) + [2, 2, 2, 3] + + Visual Factorization: + + If ``visual`` is set to ``True``, then it will return a visual + factorization of the integer. For example: + + >>> from sympy import pprint + >>> pprint(factorint(4200, visual=True)) + 3 1 2 1 + 2 *3 *5 *7 + + Note that this is achieved by using the evaluate=False flag in Mul + and Pow. If you do other manipulations with an expression where + evaluate=False, it may evaluate. Therefore, you should use the + visual option only for visualization, and use the normal dictionary + returned by visual=False if you want to perform operations on the + factors. + + You can easily switch between the two forms by sending them back to + factorint: + + >>> from sympy import Mul + >>> regular = factorint(1764); regular + {2: 2, 3: 2, 7: 2} + >>> pprint(factorint(regular)) + 2 2 2 + 2 *3 *7 + + >>> visual = factorint(1764, visual=True); pprint(visual) + 2 2 2 + 2 *3 *7 + >>> print(factorint(visual)) + {2: 2, 3: 2, 7: 2} + + If you want to send a number to be factored in a partially factored form + you can do so with a dictionary or unevaluated expression: + + >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form + {2: 10, 3: 3} + >>> factorint(Mul(4, 12, evaluate=False)) + {2: 4, 3: 1} + + The table of the output logic is: + + ====== ====== ======= ======= + Visual + ------ ---------------------- + Input True False other + ====== ====== ======= ======= + dict mul dict mul + n mul dict dict + mul mul dict dict + ====== ====== ======= ======= + + Notes + ===== + + Algorithm: + + The function switches between multiple algorithms. Trial division + quickly finds small factors (of the order 1-5 digits), and finds + all large factors if given enough time. The Pollard rho and p-1 + algorithms are used to find large factors ahead of time; they + will often find factors of the order of 10 digits within a few + seconds: + + >>> factors = factorint(12345678910111213141516) + >>> for base, exp in sorted(factors.items()): + ... print('%s %s' % (base, exp)) + ... + 2 2 + 2507191691 1 + 1231026625769 1 + + Any of these methods can optionally be disabled with the following + boolean parameters: + + - ``use_trial``: Toggle use of trial division + - ``use_rho``: Toggle use of Pollard's rho method + - ``use_pm1``: Toggle use of Pollard's p-1 method + + ``factorint`` also periodically checks if the remaining part is + a prime number or a perfect power, and in those cases stops. + + For unevaluated factorial, it uses Legendre's formula(theorem). + + + If ``verbose`` is set to ``True``, detailed progress is printed. + + See Also + ======== + + smoothness, smoothness_p, divisors + + """ + if isinstance(n, Dict): + n = dict(n) + if multiple: + fac = factorint(n, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False, multiple=False) + factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) + for p in sorted(fac)), []) + return factorlist + + factordict = {} + if visual and not isinstance(n, (Mul, dict)): + factordict = factorint(n, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False) + elif isinstance(n, Mul): + factordict = {int(k): int(v) for k, v in + n.as_powers_dict().items()} + elif isinstance(n, dict): + factordict = n + if factordict and isinstance(n, (Mul, dict)): + # check it + for key in list(factordict.keys()): + if isprime(key): + continue + e = factordict.pop(key) + d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho, + use_pm1=use_pm1, verbose=verbose, visual=False) + for k, v in d.items(): + if k in factordict: + factordict[k] += v*e + else: + factordict[k] = v*e + if visual or (type(n) is dict and + visual is not True and + visual is not False): + if factordict == {}: + return S.One + if -1 in factordict: + factordict.pop(-1) + args = [S.NegativeOne] + else: + args = [] + args.extend([Pow(*i, evaluate=False) + for i in sorted(factordict.items())]) + return Mul(*args, evaluate=False) + elif isinstance(n, (dict, Mul)): + return factordict + + assert use_trial or use_rho or use_pm1 or use_ecm + + from sympy.functions.combinatorial.factorials import factorial + if isinstance(n, factorial): + x = as_int(n.args[0]) + if x >= 20: + factors = {} + m = 2 # to initialize the if condition below + for p in sieve.primerange(2, x + 1): + if m > 1: + m, q = 0, x // p + while q != 0: + m += q + q //= p + factors[p] = m + if factors and verbose: + for k in sorted(factors): + print(factor_msg % (k, factors[k])) + if verbose: + print(complete_msg) + return factors + else: + # if n < 20!, direct computation is faster + # since it uses a lookup table + n = n.func(x) + + n = as_int(n) + if limit: + limit = int(limit) + use_ecm = False + + # special cases + if n < 0: + factors = factorint( + -n, limit=limit, use_trial=use_trial, use_rho=use_rho, + use_pm1=use_pm1, verbose=verbose, visual=False) + factors[-1] = 1 + return factors + + if limit and limit < 2: + if n == 1: + return {} + return {n: 1} + elif n < 10: + # doing this we are assured of getting a limit > 2 + # when we have to compute it later + return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1}, + {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n] + + factors = {} + + # do simplistic factorization + if verbose: + sn = str(n) + if len(sn) > 50: + print('Factoring %s' % sn[:5] + \ + '..(%i other digits)..' % (len(sn) - 10) + sn[-5:]) + else: + print('Factoring', n) + + if use_trial: + # this is the preliminary factorization for small factors + small = 2**15 + fail_max = 600 + small = min(small, limit or small) + if verbose: + print(trial_int_msg % (2, small, fail_max)) + n, next_p = _factorint_small(factors, n, small, fail_max) + else: + next_p = 2 + if factors and verbose: + for k in sorted(factors): + print(factor_msg % (k, factors[k])) + if next_p == 0: + if n > 1: + factors[int(n)] = 1 + if verbose: + print(complete_msg) + return factors + + # continue with more advanced factorization methods + + # first check if the simplistic run didn't finish + # because of the limit and check for a perfect + # power before exiting + try: + if limit and next_p > limit: + if verbose: + print('Exceeded limit:', limit) + + _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, + verbose) + + if n > 1: + factors[int(n)] = 1 + return factors + else: + # Before quitting (or continuing on)... + + # ...do a Fermat test since it's so easy and we need the + # square root anyway. Finding 2 factors is easy if they are + # "close enough." This is the big root equivalent of dividing by + # 2, 3, 5. + sqrt_n = integer_nthroot(n, 2)[0] + a = sqrt_n + 1 + a2 = a**2 + b2 = a2 - n + for i in range(3): + b, fermat = integer_nthroot(b2, 2) + if fermat: + break + b2 += 2*a + 1 # equiv to (a + 1)**2 - n + a += 1 + if fermat: + if verbose: + print(fermat_msg) + if limit: + limit -= 1 + for r in [a - b, a + b]: + facs = factorint(r, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose) + for k, v in facs.items(): + factors[k] = factors.get(k, 0) + v + raise StopIteration + + # ...see if factorization can be terminated + _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, + verbose) + + except StopIteration: + if verbose: + print(complete_msg) + return factors + + # these are the limits for trial division which will + # be attempted in parallel with pollard methods + low, high = next_p, 2*next_p + + limit = limit or sqrt_n + # add 1 to make sure limit is reached in primerange calls + limit += 1 + iteration = 0 + while 1: + + try: + high_ = high + if limit < high_: + high_ = limit + + # Trial division + if use_trial: + if verbose: + print(trial_msg % (low, high_)) + ps = sieve.primerange(low, high_) + n, found_trial = _trial(factors, n, ps, verbose) + if found_trial: + _check_termination(factors, n, limit, use_trial, use_rho, + use_pm1, verbose) + else: + found_trial = False + + if high > limit: + if verbose: + print('Exceeded limit:', limit) + if n > 1: + factors[int(n)] = 1 + raise StopIteration + + # Only used advanced methods when no small factors were found + if not found_trial: + if (use_pm1 or use_rho): + high_root = max(int(math.log(high_**0.7)), low, 3) + + # Pollard p-1 + if use_pm1: + if verbose: + print(pm1_msg % (high_root, high_)) + c = pollard_pm1(n, B=high_root, seed=high_) + if c: + # factor it and let _trial do the update + ps = factorint(c, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + + # Pollard rho + if use_rho: + max_steps = high_root + if verbose: + print(rho_msg % (1, max_steps, high_)) + c = pollard_rho(n, retries=1, max_steps=max_steps, + seed=high_) + if c: + # factor it and let _trial do the update + ps = factorint(c, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + + except StopIteration: + if verbose: + print(complete_msg) + return factors + #Use subexponential algorithms if use_ecm + #Use pollard algorithms for finding small factors for 3 iterations + #if after small factors the number of digits of n is >= 20 then use ecm + iteration += 1 + if use_ecm and iteration >= 3 and len(str(n)) >= 25: + break + low, high = high, high*2 + B1 = 10000 + B2 = 100*B1 + num_curves = 50 + while(1): + if verbose: + print(ecm_msg % (B1, B2, num_curves)) + while(1): + try: + factor = _ecm_one_factor(n, B1, B2, num_curves) + ps = factorint(factor, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + except ValueError: + break + except StopIteration: + if verbose: + print(complete_msg) + return factors + B1 *= 5 + B2 = 100*B1 + num_curves *= 4 + + +def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True, + verbose=False, visual=None, multiple=False): + r""" + Given a Rational ``r``, ``factorrat(r)`` returns a dict containing + the prime factors of ``r`` as keys and their respective multiplicities + as values. For example: + + >>> from sympy import factorrat, S + >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2) + {2: 3, 3: -2} + >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1) + {-1: 1, 3: -1, 7: -1, 47: -1} + + Please see the docstring for ``factorint`` for detailed explanations + and examples of the following keywords: + + - ``limit``: Integer limit up to which trial division is done + - ``use_trial``: Toggle use of trial division + - ``use_rho``: Toggle use of Pollard's rho method + - ``use_pm1``: Toggle use of Pollard's p-1 method + - ``verbose``: Toggle detailed printing of progress + - ``multiple``: Toggle returning a list of factors or dict + - ``visual``: Toggle product form of output + """ + if multiple: + fac = factorrat(rat, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False, multiple=False) + factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) + for p, _ in sorted(fac.items(), + key=lambda elem: elem[0] + if elem[1] > 0 + else 1/elem[0])), []) + return factorlist + + f = factorint(rat.p, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose).copy() + f = defaultdict(int, f) + for p, e in factorint(rat.q, limit=limit, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + verbose=verbose).items(): + f[p] += -e + + if len(f) > 1 and 1 in f: + del f[1] + if not visual: + return dict(f) + else: + if -1 in f: + f.pop(-1) + args = [S.NegativeOne] + else: + args = [] + args.extend([Pow(*i, evaluate=False) + for i in sorted(f.items())]) + return Mul(*args, evaluate=False) + + + +def primefactors(n, limit=None, verbose=False): + """Return a sorted list of n's prime factors, ignoring multiplicity + and any composite factor that remains if the limit was set too low + for complete factorization. Unlike factorint(), primefactors() does + not return -1 or 0. + + Examples + ======== + + >>> from sympy.ntheory import primefactors, factorint, isprime + >>> primefactors(6) + [2, 3] + >>> primefactors(-5) + [5] + + >>> sorted(factorint(123456).items()) + [(2, 6), (3, 1), (643, 1)] + >>> primefactors(123456) + [2, 3, 643] + + >>> sorted(factorint(10000000001, limit=200).items()) + [(101, 1), (99009901, 1)] + >>> isprime(99009901) + False + >>> primefactors(10000000001, limit=300) + [101] + + See Also + ======== + + divisors + """ + n = int(n) + factors = sorted(factorint(n, limit=limit, verbose=verbose).keys()) + s = [f for f in factors[:-1:] if f not in [-1, 0, 1]] + if factors and isprime(factors[-1]): + s += [factors[-1]] + return s + + +def _divisors(n, proper=False): + """Helper function for divisors which generates the divisors.""" + + factordict = factorint(n) + ps = sorted(factordict.keys()) + + def rec_gen(n=0): + if n == len(ps): + yield 1 + else: + pows = [1] + for j in range(factordict[ps[n]]): + pows.append(pows[-1] * ps[n]) + for q in rec_gen(n + 1): + for p in pows: + yield p * q + + if proper: + for p in rec_gen(): + if p != n: + yield p + else: + yield from rec_gen() + + +def divisors(n, generator=False, proper=False): + r""" + Return all divisors of n sorted from 1..n by default. + If generator is ``True`` an unordered generator is returned. + + The number of divisors of n can be quite large if there are many + prime factors (counting repeated factors). If only the number of + factors is desired use divisor_count(n). + + Examples + ======== + + >>> from sympy import divisors, divisor_count + >>> divisors(24) + [1, 2, 3, 4, 6, 8, 12, 24] + >>> divisor_count(24) + 8 + + >>> list(divisors(120, generator=True)) + [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] + + Notes + ===== + + This is a slightly modified version of Tim Peters referenced at: + https://stackoverflow.com/questions/1010381/python-factorization + + See Also + ======== + + primefactors, factorint, divisor_count + """ + + n = as_int(abs(n)) + if isprime(n): + if proper: + return [1] + return [1, n] + if n == 1: + if proper: + return [] + return [1] + if n == 0: + return [] + rv = _divisors(n, proper) + if not generator: + return sorted(rv) + return rv + + +def divisor_count(n, modulus=1, proper=False): + """ + Return the number of divisors of ``n``. If ``modulus`` is not 1 then only + those that are divisible by ``modulus`` are counted. If ``proper`` is True + then the divisor of ``n`` will not be counted. + + Examples + ======== + + >>> from sympy import divisor_count + >>> divisor_count(6) + 4 + >>> divisor_count(6, 2) + 2 + >>> divisor_count(6, proper=True) + 3 + + See Also + ======== + + factorint, divisors, totient, proper_divisor_count + + """ + + if not modulus: + return 0 + elif modulus != 1: + n, r = divmod(n, modulus) + if r: + return 0 + if n == 0: + return 0 + n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1]) + if n and proper: + n -= 1 + return n + + +def proper_divisors(n, generator=False): + """ + Return all divisors of n except n, sorted by default. + If generator is ``True`` an unordered generator is returned. + + Examples + ======== + + >>> from sympy import proper_divisors, proper_divisor_count + >>> proper_divisors(24) + [1, 2, 3, 4, 6, 8, 12] + >>> proper_divisor_count(24) + 7 + >>> list(proper_divisors(120, generator=True)) + [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60] + + See Also + ======== + + factorint, divisors, proper_divisor_count + + """ + return divisors(n, generator=generator, proper=True) + + +def proper_divisor_count(n, modulus=1): + """ + Return the number of proper divisors of ``n``. + + Examples + ======== + + >>> from sympy import proper_divisor_count + >>> proper_divisor_count(6) + 3 + >>> proper_divisor_count(6, modulus=2) + 1 + + See Also + ======== + + divisors, proper_divisors, divisor_count + + """ + return divisor_count(n, modulus=modulus, proper=True) + + +def _udivisors(n): + """Helper function for udivisors which generates the unitary divisors.""" + + factorpows = [p**e for p, e in factorint(n).items()] + for i in range(2**len(factorpows)): + d, j, k = 1, i, 0 + while j: + if (j & 1): + d *= factorpows[k] + j >>= 1 + k += 1 + yield d + + +def udivisors(n, generator=False): + r""" + Return all unitary divisors of n sorted from 1..n by default. + If generator is ``True`` an unordered generator is returned. + + The number of unitary divisors of n can be quite large if there are many + prime factors. If only the number of unitary divisors is desired use + udivisor_count(n). + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisors, udivisor_count + >>> udivisors(15) + [1, 3, 5, 15] + >>> udivisor_count(15) + 4 + + >>> sorted(udivisors(120, generator=True)) + [1, 3, 5, 8, 15, 24, 40, 120] + + See Also + ======== + + primefactors, factorint, divisors, divisor_count, udivisor_count + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Unitary_divisor + .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html + + """ + + n = as_int(abs(n)) + if isprime(n): + return [1, n] + if n == 1: + return [1] + if n == 0: + return [] + rv = _udivisors(n) + if not generator: + return sorted(rv) + return rv + + +def udivisor_count(n): + """ + Return the number of unitary divisors of ``n``. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisor_count + >>> udivisor_count(120) + 8 + + See Also + ======== + + factorint, divisors, udivisors, divisor_count, totient + + References + ========== + + .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html + + """ + + if n == 0: + return 0 + return 2**len([p for p in factorint(n) if p > 1]) + + +def _antidivisors(n): + """Helper function for antidivisors which generates the antidivisors.""" + + for d in _divisors(n): + y = 2*d + if n > y and n % y: + yield y + for d in _divisors(2*n-1): + if n > d >= 2 and n % d: + yield d + for d in _divisors(2*n+1): + if n > d >= 2 and n % d: + yield d + + +def antidivisors(n, generator=False): + r""" + Return all antidivisors of n sorted from 1..n by default. + + Antidivisors [1]_ of n are numbers that do not divide n by the largest + possible margin. If generator is True an unordered generator is returned. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import antidivisors + >>> antidivisors(24) + [7, 16] + + >>> sorted(antidivisors(128, generator=True)) + [3, 5, 15, 17, 51, 85] + + See Also + ======== + + primefactors, factorint, divisors, divisor_count, antidivisor_count + + References + ========== + + .. [1] definition is described in https://oeis.org/A066272/a066272a.html + + """ + + n = as_int(abs(n)) + if n <= 2: + return [] + rv = _antidivisors(n) + if not generator: + return sorted(rv) + return rv + + +def antidivisor_count(n): + """ + Return the number of antidivisors [1]_ of ``n``. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory.factor_ import antidivisor_count + >>> antidivisor_count(13) + 4 + >>> antidivisor_count(27) + 5 + + See Also + ======== + + factorint, divisors, antidivisors, divisor_count, totient + + References + ========== + + .. [1] formula from https://oeis.org/A066272 + + """ + + n = as_int(abs(n)) + if n <= 2: + return 0 + return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \ + divisor_count(n) - divisor_count(n, 2) - 5 + + +class totient(Function): + r""" + Calculate the Euler totient function phi(n) + + ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n + that are relatively prime to n. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory import totient + >>> totient(1) + 1 + >>> totient(25) + 20 + >>> totient(45) == totient(5)*totient(9) + True + + See Also + ======== + + divisor_count + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function + .. [2] https://mathworld.wolfram.com/TotientFunction.html + + """ + @classmethod + def eval(cls, n): + if n.is_Integer: + if n < 1: + raise ValueError("n must be a positive integer") + factors = factorint(n) + return cls._from_factors(factors) + elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False): + raise ValueError("n must be a positive integer") + + def _eval_is_integer(self): + return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) + + @classmethod + def _from_distinct_primes(self, *args): + """Subroutine to compute totient from the list of assumed + distinct primes + + Examples + ======== + + >>> from sympy.ntheory.factor_ import totient + >>> totient._from_distinct_primes(5, 7) + 24 + """ + return reduce(lambda i, j: i * (j-1), args, 1) + + @classmethod + def _from_factors(self, factors): + """Subroutine to compute totient from already-computed factors + + Examples + ======== + + >>> from sympy.ntheory.factor_ import totient + >>> totient._from_factors({5: 2}) + 20 + """ + t = 1 + for p, k in factors.items(): + t *= (p - 1) * p**(k - 1) + return t + + +class reduced_totient(Function): + r""" + Calculate the Carmichael reduced totient function lambda(n) + + ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that + `k^m \equiv 1 \mod n` for all k relatively prime to n. + + Examples + ======== + + >>> from sympy.ntheory import reduced_totient + >>> reduced_totient(1) + 1 + >>> reduced_totient(8) + 2 + >>> reduced_totient(30) + 4 + + See Also + ======== + + totient + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Carmichael_function + .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html + + """ + @classmethod + def eval(cls, n): + if n.is_Integer: + if n < 1: + raise ValueError("n must be a positive integer") + factors = factorint(n) + return cls._from_factors(factors) + + @classmethod + def _from_factors(self, factors): + """Subroutine to compute totient from already-computed factors + """ + t = 1 + for p, k in factors.items(): + if p == 2 and k > 2: + t = ilcm(t, 2**(k - 2)) + else: + t = ilcm(t, (p - 1) * p**(k - 1)) + return t + + @classmethod + def _from_distinct_primes(self, *args): + """Subroutine to compute totient from the list of assumed + distinct primes + """ + args = [p - 1 for p in args] + return ilcm(*args) + + def _eval_is_integer(self): + return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) + + +class divisor_sigma(Function): + r""" + Calculate the divisor function `\sigma_k(n)` for positive integer n + + ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])`` + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots + + p_i^{m_ik}). + + Parameters + ========== + + n : integer + + k : integer, optional + power of divisors in the sum + + for k = 0, 1: + ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)`` + ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))`` + + Default for k is 1. + + Examples + ======== + + >>> from sympy.ntheory import divisor_sigma + >>> divisor_sigma(18, 0) + 6 + >>> divisor_sigma(39, 1) + 56 + >>> divisor_sigma(12, 2) + 210 + >>> divisor_sigma(37) + 38 + + See Also + ======== + + divisor_count, totient, divisors, factorint + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Divisor_function + + """ + + @classmethod + def eval(cls, n, k=S.One): + k = sympify(k) + + if n.is_prime: + return 1 + n**k + + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + elif k.is_Integer: + k = int(k) + return Integer(math.prod( + (p**(k*(e + 1)) - 1)//(p**k - 1) if k != 0 + else e + 1 for p, e in factorint(n).items())) + else: + return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0 + else e + 1 for p, e in factorint(n).items()]) + + if n.is_integer: # symbolic case + args = [] + for p, e in (_.as_base_exp() for _ in Mul.make_args(n)): + if p.is_prime and e.is_positive: + args.append((p**(k*(e + 1)) - 1)/(p**k - 1) if + k != 0 else e + 1) + else: + return + return Mul(*args) + + +def core(n, t=2): + r""" + Calculate core(n, t) = `core_t(n)` of a positive integer n + + ``core_2(n)`` is equal to the squarefree part of n + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}. + + Parameters + ========== + + n : integer + + t : integer + core(n, t) calculates the t-th power free part of n + + ``core(n, 2)`` is the squarefree part of ``n`` + ``core(n, 3)`` is the cubefree part of ``n`` + + Default for t is 2. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import core + >>> core(24, 2) + 6 + >>> core(9424, 3) + 1178 + >>> core(379238) + 379238 + >>> core(15**11, 10) + 15 + + See Also + ======== + + factorint, sympy.solvers.diophantine.diophantine.square_factor + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core + + """ + + n = as_int(n) + t = as_int(t) + if n <= 0: + raise ValueError("n must be a positive integer") + elif t <= 1: + raise ValueError("t must be >= 2") + else: + y = 1 + for p, e in factorint(n).items(): + y *= p**(e % t) + return y + + +class udivisor_sigma(Function): + r""" + Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n + + ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])`` + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}). + + Parameters + ========== + + k : power of divisors in the sum + + for k = 0, 1: + ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)`` + ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))`` + + Default for k is 1. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisor_sigma + >>> udivisor_sigma(18, 0) + 4 + >>> udivisor_sigma(74, 1) + 114 + >>> udivisor_sigma(36, 3) + 47450 + >>> udivisor_sigma(111) + 152 + + See Also + ======== + + divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma, + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html + + """ + + @classmethod + def eval(cls, n, k=S.One): + k = sympify(k) + if n.is_prime: + return 1 + n**k + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return Mul(*[1+p**(k*e) for p, e in factorint(n).items()]) + + +class primenu(Function): + r""" + Calculate the number of distinct prime factors for a positive integer n. + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^k p_i^{m_i}, + + then ``primenu(n)`` or `\nu(n)` is: + + .. math :: + \nu(n) = k. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import primenu + >>> primenu(1) + 0 + >>> primenu(30) + 3 + + See Also + ======== + + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/PrimeFactor.html + + """ + + @classmethod + def eval(cls, n): + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return len(factorint(n).keys()) + + +class primeomega(Function): + r""" + Calculate the number of prime factors counting multiplicities for a + positive integer n. + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^k p_i^{m_i}, + + then ``primeomega(n)`` or `\Omega(n)` is: + + .. math :: + \Omega(n) = \sum_{i=1}^k m_i. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import primeomega + >>> primeomega(1) + 0 + >>> primeomega(20) + 3 + + See Also + ======== + + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/PrimeFactor.html + + """ + + @classmethod + def eval(cls, n): + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return sum(factorint(n).values()) + + +def mersenne_prime_exponent(nth): + """Returns the exponent ``i`` for the nth Mersenne prime (which + has the form `2^i - 1`). + + Examples + ======== + + >>> from sympy.ntheory.factor_ import mersenne_prime_exponent + >>> mersenne_prime_exponent(1) + 2 + >>> mersenne_prime_exponent(20) + 4423 + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2") + if n > 51: + raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51") + return MERSENNE_PRIME_EXPONENTS[n - 1] + + +def is_perfect(n): + """Returns True if ``n`` is a perfect number, else False. + + A perfect number is equal to the sum of its positive, proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_perfect, divisors, divisor_sigma + >>> is_perfect(20) + False + >>> is_perfect(6) + True + >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1]) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/PerfectNumber.html + .. [2] https://en.wikipedia.org/wiki/Perfect_number + + """ + + n = as_int(n) + if _isperfect(n): + return True + + # all perfect numbers for Mersenne primes with exponents + # less than or equal to 43112609 are known + iknow = MERSENNE_PRIME_EXPONENTS.index(43112609) + if iknow <= len(PERFECT) - 1 and n <= PERFECT[iknow]: + # there may be gaps between this and larger known values + # so only conclude in the range for which all values + # are known + return False + if n%2 == 0: + last2 = n % 100 + if last2 != 28 and last2 % 10 != 6: + return False + r, b = integer_nthroot(1 + 8*n, 2) + if not b: + return False + m, x = divmod(1 + r, 4) + if x: + return False + e, b = integer_log(m, 2) + if not b: + return False + else: + if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/ + return False + if n % 105 == 0: # not divis by 105 + return False + if not any(n%m == r for m, r in [(12, 1), (468, 117), (324, 81)]): + return False + # there are many criteria that the factor structure of n + # must meet; since we will have to factor it to test the + # structure we will have the factors and can then check + # to see whether it is a perfect number or not. So we + # skip the structure checks and go straight to the final + # test below. + rv = divisor_sigma(n) - n + if rv == n: + if n%2 == 0: + raise ValueError(filldedent(''' + This even number is perfect and is associated with a + Mersenne Prime, 2^%s - 1. It should be + added to SymPy.''' % (e + 1))) + else: + raise ValueError(filldedent('''In 1888, Sylvester stated: " + ...a prolonged meditation on the subject has satisfied + me that the existence of any one such [odd perfect number] + -- its escape, so to say, from the complex web of conditions + which hem it in on all sides -- would be little short of a + miracle." I guess SymPy just found that miracle and it + factors like this: %s''' % factorint(n))) + + +def is_mersenne_prime(n): + """Returns True if ``n`` is a Mersenne prime, else False. + + A Mersenne prime is a prime number having the form `2^i - 1`. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_mersenne_prime + >>> is_mersenne_prime(6) + False + >>> is_mersenne_prime(127) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/MersennePrime.html + + """ + + n = as_int(n) + if _ismersenneprime(n): + return True + if not isprime(n): + return False + r, b = integer_log(n + 1, 2) + if not b: + return False + raise ValueError(filldedent(''' + This Mersenne Prime, 2^%s - 1, should + be added to SymPy's known values.''' % r)) + + +def abundance(n): + """Returns the difference between the sum of the positive + proper divisors of a number and the number. + + Examples + ======== + + >>> from sympy.ntheory import abundance, is_perfect, is_abundant + >>> abundance(6) + 0 + >>> is_perfect(6) + True + >>> abundance(10) + -2 + >>> is_abundant(10) + False + """ + return divisor_sigma(n, 1) - 2 * n + + +def is_abundant(n): + """Returns True if ``n`` is an abundant number, else False. + + A abundant number is smaller than the sum of its positive proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_abundant + >>> is_abundant(20) + True + >>> is_abundant(15) + False + + References + ========== + + .. [1] https://mathworld.wolfram.com/AbundantNumber.html + + """ + n = as_int(n) + if is_perfect(n): + return False + return n % 6 == 0 or bool(abundance(n) > 0) + + +def is_deficient(n): + """Returns True if ``n`` is a deficient number, else False. + + A deficient number is greater than the sum of its positive proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_deficient + >>> is_deficient(20) + False + >>> is_deficient(15) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/DeficientNumber.html + + """ + n = as_int(n) + if is_perfect(n): + return False + return bool(abundance(n) < 0) + + +def is_amicable(m, n): + """Returns True if the numbers `m` and `n` are "amicable", else False. + + Amicable numbers are two different numbers so related that the sum + of the proper divisors of each is equal to that of the other. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_amicable, divisor_sigma + >>> is_amicable(220, 284) + True + >>> divisor_sigma(220) == divisor_sigma(284) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Amicable_numbers + + """ + if m == n: + return False + a, b = (divisor_sigma(i) for i in (m, n)) + return a == b == (m + n) + + +def dra(n, b): + """ + Returns the additive digital root of a natural number ``n`` in base ``b`` + which is a single digit value obtained by an iterative process of summing + digits, on each iteration using the result from the previous iteration to + compute a digit sum. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import dra + >>> dra(3110, 12) + 8 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Digital_root + + """ + + num = abs(as_int(n)) + b = as_int(b) + if b <= 1: + raise ValueError("Base should be an integer greater than 1") + + if num == 0: + return 0 + + return (1 + (num - 1) % (b - 1)) + + +def drm(n, b): + """ + Returns the multiplicative digital root of a natural number ``n`` in a given + base ``b`` which is a single digit value obtained by an iterative process of + multiplying digits, on each iteration using the result from the previous + iteration to compute the digit multiplication. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import drm + >>> drm(9876, 10) + 0 + + >>> drm(49, 10) + 8 + + References + ========== + + .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html + + """ + + n = abs(as_int(n)) + b = as_int(b) + if b <= 1: + raise ValueError("Base should be an integer greater than 1") + while n > b: + mul = 1 + while n > 1: + n, r = divmod(n, b) + if r == 0: + return 0 + mul *= r + n = mul + return n diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/generate.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..3814427daf9a08aa87423207eb132a824bcb6cb9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/generate.py @@ -0,0 +1,1037 @@ +""" +Generating and counting primes. + +""" + +import random +from bisect import bisect +from itertools import count +# Using arrays for sieving instead of lists greatly reduces +# memory consumption +from array import array as _array + +from sympy.core.function import Function +from sympy.core.singleton import S +from .primetest import isprime +from sympy.utilities.misc import as_int + + +def _azeros(n): + return _array('l', [0]*n) + + +def _aset(*v): + return _array('l', v) + + +def _arange(a, b): + return _array('l', range(a, b)) + + +def _as_int_ceiling(a): + """ Wrapping ceiling in as_int will raise an error if there was a problem + determining whether the expression was exactly an integer or not.""" + from sympy.functions.elementary.integers import ceiling + return as_int(ceiling(a)) + + +class Sieve: + """An infinite list of prime numbers, implemented as a dynamically + growing sieve of Eratosthenes. When a lookup is requested involving + an odd number that has not been sieved, the sieve is automatically + extended up to that number. + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> 25 in sieve + False + >>> sieve._list + array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) + """ + + # data shared (and updated) by all Sieve instances + def __init__(self): + self._n = 6 + self._list = _aset(2, 3, 5, 7, 11, 13) # primes + self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient + self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius + assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist)) + + def __repr__(self): + return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n" + "%s sieve (%i): %i, %i, %i, ... %i, %i\n" + "%s sieve (%i): %i, %i, %i, ... %i, %i>") % ( + 'prime', len(self._list), + self._list[0], self._list[1], self._list[2], + self._list[-2], self._list[-1], + 'totient', len(self._tlist), + self._tlist[0], self._tlist[1], + self._tlist[2], self._tlist[-2], self._tlist[-1], + 'mobius', len(self._mlist), + self._mlist[0], self._mlist[1], + self._mlist[2], self._mlist[-2], self._mlist[-1]) + + def _reset(self, prime=None, totient=None, mobius=None): + """Reset all caches (default). To reset one or more set the + desired keyword to True.""" + if all(i is None for i in (prime, totient, mobius)): + prime = totient = mobius = True + if prime: + self._list = self._list[:self._n] + if totient: + self._tlist = self._tlist[:self._n] + if mobius: + self._mlist = self._mlist[:self._n] + + def extend(self, n): + """Grow the sieve to cover all primes <= n (a real number). + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> sieve.extend(30) + >>> sieve[10] == 29 + True + """ + n = int(n) + if n <= self._list[-1]: + return + + # We need to sieve against all bases up to sqrt(n). + # This is a recursive call that will do nothing if there are enough + # known bases already. + maxbase = int(n**0.5) + 1 + self.extend(maxbase) + + # Create a new sieve starting from sqrt(n) + begin = self._list[-1] + 1 + newsieve = _arange(begin, n + 1) + + # Now eliminate all multiples of primes in [2, sqrt(n)] + for p in self.primerange(maxbase): + # Start counting at a multiple of p, offsetting + # the index to account for the new sieve's base index + startindex = (-begin) % p + for i in range(startindex, len(newsieve), p): + newsieve[i] = 0 + + # Merge the sieves + self._list += _array('l', [x for x in newsieve if x]) + + def extend_to_no(self, i): + """Extend to include the ith prime number. + + Parameters + ========== + + i : integer + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> sieve.extend_to_no(9) + >>> sieve._list + array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) + + Notes + ===== + + The list is extended by 50% if it is too short, so it is + likely that it will be longer than requested. + """ + i = as_int(i) + while len(self._list) < i: + self.extend(int(self._list[-1] * 1.5)) + + def primerange(self, a, b=None): + """Generate all prime numbers in the range [2, a) or [a, b). + + Examples + ======== + + >>> from sympy import sieve, prime + + All primes less than 19: + + >>> print([i for i in sieve.primerange(19)]) + [2, 3, 5, 7, 11, 13, 17] + + All primes greater than or equal to 7 and less than 19: + + >>> print([i for i in sieve.primerange(7, 19)]) + [7, 11, 13, 17] + + All primes through the 10th prime + + >>> list(sieve.primerange(prime(10) + 1)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + """ + + if b is None: + b = _as_int_ceiling(a) + a = 2 + else: + a = max(2, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + if a >= b: + return + self.extend(b) + i = self.search(a)[1] + maxi = len(self._list) + 1 + while i < maxi: + p = self._list[i - 1] + if p < b: + yield p + i += 1 + else: + return + + def totientrange(self, a, b): + """Generate all totient numbers for the range [a, b). + + Examples + ======== + + >>> from sympy import sieve + >>> print([i for i in sieve.totientrange(7, 18)]) + [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16] + """ + a = max(1, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + n = len(self._tlist) + if a >= b: + return + elif b <= n: + for i in range(a, b): + yield self._tlist[i] + else: + self._tlist += _arange(n, b) + for i in range(1, n): + ti = self._tlist[i] + startindex = (n + i - 1) // i * i + for j in range(startindex, b, i): + self._tlist[j] -= ti + if i >= a: + yield ti + + for i in range(n, b): + ti = self._tlist[i] + for j in range(2 * i, b, i): + self._tlist[j] -= ti + if i >= a: + yield ti + + def mobiusrange(self, a, b): + """Generate all mobius numbers for the range [a, b). + + Parameters + ========== + + a : integer + First number in range + + b : integer + First number outside of range + + Examples + ======== + + >>> from sympy import sieve + >>> print([i for i in sieve.mobiusrange(7, 18)]) + [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1] + """ + a = max(1, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + n = len(self._mlist) + if a >= b: + return + elif b <= n: + for i in range(a, b): + yield self._mlist[i] + else: + self._mlist += _azeros(b - n) + for i in range(1, n): + mi = self._mlist[i] + startindex = (n + i - 1) // i * i + for j in range(startindex, b, i): + self._mlist[j] -= mi + if i >= a: + yield mi + + for i in range(n, b): + mi = self._mlist[i] + for j in range(2 * i, b, i): + self._mlist[j] -= mi + if i >= a: + yield mi + + def search(self, n): + """Return the indices i, j of the primes that bound n. + + If n is prime then i == j. + + Although n can be an expression, if ceiling cannot convert + it to an integer then an n error will be raised. + + Examples + ======== + + >>> from sympy import sieve + >>> sieve.search(25) + (9, 10) + >>> sieve.search(23) + (9, 9) + """ + test = _as_int_ceiling(n) + n = as_int(n) + if n < 2: + raise ValueError("n should be >= 2 but got: %s" % n) + if n > self._list[-1]: + self.extend(n) + b = bisect(self._list, n) + if self._list[b - 1] == test: + return b, b + else: + return b, b + 1 + + def __contains__(self, n): + try: + n = as_int(n) + assert n >= 2 + except (ValueError, AssertionError): + return False + if n % 2 == 0: + return n == 2 + a, b = self.search(n) + return a == b + + def __iter__(self): + for n in count(1): + yield self[n] + + def __getitem__(self, n): + """Return the nth prime number""" + if isinstance(n, slice): + self.extend_to_no(n.stop) + # Python 2.7 slices have 0 instead of None for start, so + # we can't default to 1. + start = n.start if n.start is not None else 0 + if start < 1: + # sieve[:5] would be empty (starting at -1), let's + # just be explicit and raise. + raise IndexError("Sieve indices start at 1.") + return self._list[start - 1:n.stop - 1:n.step] + else: + if n < 1: + # offset is one, so forbid explicit access to sieve[0] + # (would surprisingly return the last one). + raise IndexError("Sieve indices start at 1.") + n = as_int(n) + self.extend_to_no(n) + return self._list[n - 1] + +# Generate a global object for repeated use in trial division etc +sieve = Sieve() + + +def prime(nth): + r""" Return the nth prime, with the primes indexed as prime(1) = 2, + prime(2) = 3, etc.... The nth prime is approximately $n\log(n)$. + + Logarithmic integral of $x$ is a pretty nice approximation for number of + primes $\le x$, i.e. + li(x) ~ pi(x) + In fact, for the numbers we are concerned about( x<1e11 ), + li(x) - pi(x) < 50000 + + Also, + li(x) > pi(x) can be safely assumed for the numbers which + can be evaluated by this function. + + Here, we find the least integer m such that li(m) > n using binary search. + Now pi(m-1) < li(m-1) <= n, + + We find pi(m - 1) using primepi function. + + Starting from m, we have to find n - pi(m-1) more primes. + + For the inputs this implementation can handle, we will have to test + primality for at max about 10**5 numbers, to get our answer. + + Examples + ======== + + >>> from sympy import prime + >>> prime(10) + 29 + >>> prime(1) + 2 + >>> prime(100000) + 1299709 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + primepi : Return the number of primes less than or equal to n + + References + ========== + + .. [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 + .. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number + .. [3] https://en.wikipedia.org/wiki/Skewes%27_number + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; prime(1) == 2") + if n <= len(sieve._list): + return sieve[n] + + from sympy.functions.elementary.exponential import log + from sympy.functions.special.error_functions import li + a = 2 # Lower bound for binary search + b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. + + while a < b: + mid = (a + b) >> 1 + if li(mid) > n: + b = mid + else: + a = mid + 1 + n_primes = primepi(a - 1) + while n_primes < n: + if isprime(a): + n_primes += 1 + a += 1 + return a - 1 + + +class primepi(Function): + r""" Represents the prime counting function pi(n) = the number + of prime numbers less than or equal to n. + + Algorithm Description: + + In sieve method, we remove all multiples of prime p + except p itself. + + Let phi(i,j) be the number of integers 2 <= k <= i + which remain after sieving from primes less than + or equal to j. + Clearly, pi(n) = phi(n, sqrt(n)) + + If j is not a prime, + phi(i,j) = phi(i, j - 1) + + if j is a prime, + We remove all numbers(except j) whose + smallest prime factor is j. + + Let $x= j \times a$ be such a number, where $2 \le a \le i / j$ + Now, after sieving from primes $\le j - 1$, + a must remain + (because x, and hence a has no prime factor $\le j - 1$) + Clearly, there are phi(i / j, j - 1) such a + which remain on sieving from primes $\le j - 1$ + + Now, if a is a prime less than equal to j - 1, + $x= j \times a$ has smallest prime factor = a, and + has already been removed(by sieving from a). + So, we do not need to remove it again. + (Note: there will be pi(j - 1) such x) + + Thus, number of x, that will be removed are: + phi(i / j, j - 1) - phi(j - 1, j - 1) + (Note that pi(j - 1) = phi(j - 1, j - 1)) + + $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1) + + So,following recursion is used and implemented as dp: + + phi(a, b) = phi(a, b - 1), if b is not a prime + phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime + + Clearly a is always of the form floor(n / k), + which can take at most $2\sqrt{n}$ values. + Two arrays arr1,arr2 are maintained + arr1[i] = phi(i, j), + arr2[i] = phi(n // i, j) + + Finally the answer is arr2[1] + + Examples + ======== + + >>> from sympy import primepi, prime, prevprime, isprime + >>> primepi(25) + 9 + + So there are 9 primes less than or equal to 25. Is 25 prime? + + >>> isprime(25) + False + + It is not. So the first prime less than 25 must be the + 9th prime: + + >>> prevprime(25) == prime(9) + True + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + prime : Return the nth prime + """ + @classmethod + def eval(cls, n): + if n is S.Infinity: + return S.Infinity + if n is S.NegativeInfinity: + return S.Zero + + try: + n = int(n) + except TypeError: + if n.is_real == False or n is S.NaN: + raise ValueError("n must be real") + return + + if n < 2: + return S.Zero + if n <= sieve._list[-1]: + return S(sieve.search(n)[0]) + lim = int(n ** 0.5) + lim -= 1 + lim = max(lim, 0) + while lim * lim <= n: + lim += 1 + lim -= 1 + arr1 = [0] * (lim + 1) + arr2 = [0] * (lim + 1) + for i in range(1, lim + 1): + arr1[i] = i - 1 + arr2[i] = n // i - 1 + for i in range(2, lim + 1): + # Presently, arr1[k]=phi(k,i - 1), + # arr2[k] = phi(n // k,i - 1) + if arr1[i] == arr1[i - 1]: + continue + p = arr1[i - 1] + for j in range(1, min(n // (i * i), lim) + 1): + st = i * j + if st <= lim: + arr2[j] -= arr2[st] - p + else: + arr2[j] -= arr1[n // st] - p + lim2 = min(lim, i * i - 1) + for j in range(lim, lim2, -1): + arr1[j] -= arr1[j // i] - p + return S(arr2[1]) + + +def nextprime(n, ith=1): + """ Return the ith prime greater than n. + + i must be an integer. + + Notes + ===== + + Potential primes are located at 6*j +/- 1. This + property is used during searching. + + >>> from sympy import nextprime + >>> [(i, nextprime(i)) for i in range(10, 15)] + [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] + >>> nextprime(2, ith=2) # the 2nd prime after 2 + 5 + + See Also + ======== + + prevprime : Return the largest prime smaller than n + primerange : Generate all primes in a given range + + """ + n = int(n) + i = as_int(ith) + if i > 1: + pr = n + j = 1 + while 1: + pr = nextprime(pr) + j += 1 + if j > i: + break + return pr + + if n < 2: + return 2 + if n < 7: + return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] + if n <= sieve._list[-2]: + l, u = sieve.search(n) + if l == u: + return sieve[u + 1] + else: + return sieve[u] + nn = 6*(n//6) + if nn == n: + n += 1 + if isprime(n): + return n + n += 4 + elif n - nn == 5: + n += 2 + if isprime(n): + return n + n += 4 + else: + n = nn + 5 + while 1: + if isprime(n): + return n + n += 2 + if isprime(n): + return n + n += 4 + + +def prevprime(n): + """ Return the largest prime smaller than n. + + Notes + ===== + + Potential primes are located at 6*j +/- 1. This + property is used during searching. + + >>> from sympy import prevprime + >>> [(i, prevprime(i)) for i in range(10, 15)] + [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] + + See Also + ======== + + nextprime : Return the ith prime greater than n + primerange : Generates all primes in a given range + """ + n = _as_int_ceiling(n) + if n < 3: + raise ValueError("no preceding primes") + if n < 8: + return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] + if n <= sieve._list[-1]: + l, u = sieve.search(n) + if l == u: + return sieve[l-1] + else: + return sieve[l] + nn = 6*(n//6) + if n - nn <= 1: + n = nn - 1 + if isprime(n): + return n + n -= 4 + else: + n = nn + 1 + while 1: + if isprime(n): + return n + n -= 2 + if isprime(n): + return n + n -= 4 + + +def primerange(a, b=None): + """ Generate a list of all prime numbers in the range [2, a), + or [a, b). + + If the range exists in the default sieve, the values will + be returned from there; otherwise values will be returned + but will not modify the sieve. + + Examples + ======== + + >>> from sympy import primerange, prime + + All primes less than 19: + + >>> list(primerange(19)) + [2, 3, 5, 7, 11, 13, 17] + + All primes greater than or equal to 7 and less than 19: + + >>> list(primerange(7, 19)) + [7, 11, 13, 17] + + All primes through the 10th prime + + >>> list(primerange(prime(10) + 1)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + The Sieve method, primerange, is generally faster but it will + occupy more memory as the sieve stores values. The default + instance of Sieve, named sieve, can be used: + + >>> from sympy import sieve + >>> list(sieve.primerange(1, 30)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + Notes + ===== + + Some famous conjectures about the occurrence of primes in a given + range are [1]: + + - Twin primes: though often not, the following will give 2 primes + an infinite number of times: + primerange(6*n - 1, 6*n + 2) + - Legendre's: the following always yields at least one prime + primerange(n**2, (n+1)**2+1) + - Bertrand's (proven): there is always a prime in the range + primerange(n, 2*n) + - Brocard's: there are at least four primes in the range + primerange(prime(n)**2, prime(n+1)**2) + + The average gap between primes is log(n) [2]; the gap between + primes can be arbitrarily large since sequences of composite + numbers are arbitrarily large, e.g. the numbers in the sequence + n! + 2, n! + 3 ... n! + n are all composite. + + See Also + ======== + + prime : Return the nth prime + nextprime : Return the ith prime greater than n + prevprime : Return the largest prime smaller than n + randprime : Returns a random prime in a given range + primorial : Returns the product of primes based on condition + Sieve.primerange : return range from already computed primes + or extend the sieve to contain the requested + range. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Prime_number + .. [2] https://primes.utm.edu/notes/gaps.html + """ + if b is None: + a, b = 2, a + if a >= b: + return + # if we already have the range, return it + if b <= sieve._list[-1]: + yield from sieve.primerange(a, b) + return + # otherwise compute, without storing, the desired range. + + a = _as_int_ceiling(a) - 1 + b = _as_int_ceiling(b) + while 1: + a = nextprime(a) + if a < b: + yield a + else: + return + + +def randprime(a, b): + """ Return a random prime number in the range [a, b). + + Bertrand's postulate assures that + randprime(a, 2*a) will always succeed for a > 1. + + Examples + ======== + + >>> from sympy import randprime, isprime + >>> randprime(1, 30) #doctest: +SKIP + 13 + >>> isprime(randprime(1, 30)) + True + + See Also + ======== + + primerange : Generate all primes in a given range + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate + + """ + if a >= b: + return + a, b = map(int, (a, b)) + n = random.randint(a - 1, b) + p = nextprime(n) + if p >= b: + p = prevprime(b) + if p < a: + raise ValueError("no primes exist in the specified range") + return p + + +def primorial(n, nth=True): + """ + Returns the product of the first n primes (default) or + the primes less than or equal to n (when ``nth=False``). + + Examples + ======== + + >>> from sympy.ntheory.generate import primorial, primerange + >>> from sympy import factorint, Mul, primefactors, sqrt + >>> primorial(4) # the first 4 primes are 2, 3, 5, 7 + 210 + >>> primorial(4, nth=False) # primes <= 4 are 2 and 3 + 6 + >>> primorial(1) + 2 + >>> primorial(1, nth=False) + 1 + >>> primorial(sqrt(101), nth=False) + 210 + + One can argue that the primes are infinite since if you take + a set of primes and multiply them together (e.g. the primorial) and + then add or subtract 1, the result cannot be divided by any of the + original factors, hence either 1 or more new primes must divide this + product of primes. + + In this case, the number itself is a new prime: + + >>> factorint(primorial(4) + 1) + {211: 1} + + In this case two new primes are the factors: + + >>> factorint(primorial(4) - 1) + {11: 1, 19: 1} + + Here, some primes smaller and larger than the primes multiplied together + are obtained: + + >>> p = list(primerange(10, 20)) + >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p))) + [2, 5, 31, 149] + + See Also + ======== + + primerange : Generate all primes in a given range + + """ + if nth: + n = as_int(n) + else: + n = int(n) + if n < 1: + raise ValueError("primorial argument must be >= 1") + p = 1 + if nth: + for i in range(1, n + 1): + p *= prime(i) + else: + for i in primerange(2, n + 1): + p *= i + return p + + +def cycle_length(f, x0, nmax=None, values=False): + """For a given iterated sequence, return a generator that gives + the length of the iterated cycle (lambda) and the length of terms + before the cycle begins (mu); if ``values`` is True then the + terms of the sequence will be returned instead. The sequence is + started with value ``x0``. + + Note: more than the first lambda + mu terms may be returned and this + is the cost of cycle detection with Brent's method; there are, however, + generally less terms calculated than would have been calculated if the + proper ending point were determined, e.g. by using Floyd's method. + + >>> from sympy.ntheory.generate import cycle_length + + This will yield successive values of i <-- func(i): + + >>> def iter(func, i): + ... while 1: + ... ii = func(i) + ... yield ii + ... i = ii + ... + + A function is defined: + + >>> func = lambda i: (i**2 + 1) % 51 + + and given a seed of 4 and the mu and lambda terms calculated: + + >>> next(cycle_length(func, 4)) + (6, 2) + + We can see what is meant by looking at the output: + + >>> n = cycle_length(func, 4, values=True) + >>> list(ni for ni in n) + [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] + + There are 6 repeating values after the first 2. + + If a sequence is suspected of being longer than you might wish, ``nmax`` + can be used to exit early (and mu will be returned as None): + + >>> next(cycle_length(func, 4, nmax = 4)) + (4, None) + >>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)] + [17, 35, 2, 5] + + Code modified from: + https://en.wikipedia.org/wiki/Cycle_detection. + """ + + nmax = int(nmax or 0) + + # main phase: search successive powers of two + power = lam = 1 + tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0. + i = 0 + while tortoise != hare and (not nmax or i < nmax): + i += 1 + if power == lam: # time to start a new power of two? + tortoise = hare + power *= 2 + lam = 0 + if values: + yield hare + hare = f(hare) + lam += 1 + if nmax and i == nmax: + if values: + return + else: + yield nmax, None + return + if not values: + # Find the position of the first repetition of length lambda + mu = 0 + tortoise = hare = x0 + for i in range(lam): + hare = f(hare) + while tortoise != hare: + tortoise = f(tortoise) + hare = f(hare) + mu += 1 + if mu: + mu -= 1 + yield lam, mu + + +def composite(nth): + """ Return the nth composite number, with the composite numbers indexed as + composite(1) = 4, composite(2) = 6, etc.... + + Examples + ======== + + >>> from sympy import composite + >>> composite(36) + 52 + >>> composite(1) + 4 + >>> composite(17737) + 20000 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + primepi : Return the number of primes less than or equal to n + prime : Return the nth prime + compositepi : Return the number of positive composite numbers less than or equal to n + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; composite(1) == 4") + composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18] + if n <= 10: + return composite_arr[n - 1] + + a, b = 4, sieve._list[-1] + if n <= b - primepi(b) - 1: + while a < b - 1: + mid = (a + b) >> 1 + if mid - primepi(mid) - 1 > n: + b = mid + else: + a = mid + if isprime(a): + a -= 1 + return a + + from sympy.functions.elementary.exponential import log + from sympy.functions.special.error_functions import li + a = 4 # Lower bound for binary search + b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. + + while a < b: + mid = (a + b) >> 1 + if mid - li(mid) - 1 > n: + b = mid + else: + a = mid + 1 + + n_composites = a - primepi(a) - 1 + while n_composites > n: + if not isprime(a): + n_composites -= 1 + a -= 1 + if isprime(a): + a -= 1 + return a + + +def compositepi(n): + """ Return the number of positive composite numbers less than or equal to n. + The first positive composite is 4, i.e. compositepi(4) = 1. + + Examples + ======== + + >>> from sympy import compositepi + >>> compositepi(25) + 15 + >>> compositepi(1000) + 831 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + prime : Return the nth prime + primepi : Return the number of primes less than or equal to n + composite : Return the nth composite number + """ + n = int(n) + if n < 4: + return 0 + return n - primepi(n) - 1 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/modular.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/modular.py new file mode 100644 index 0000000000000000000000000000000000000000..2962f511ff1473978ca9fb624e202094474b00dd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/modular.py @@ -0,0 +1,255 @@ +from functools import reduce +from math import prod + +from sympy.core.numbers import igcdex, igcd +from sympy.ntheory.primetest import isprime +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2 +from sympy.utilities.misc import as_int + + +def symmetric_residue(a, m): + """Return the residual mod m such that it is within half of the modulus. + + >>> from sympy.ntheory.modular import symmetric_residue + >>> symmetric_residue(1, 6) + 1 + >>> symmetric_residue(4, 6) + -2 + """ + if a <= m // 2: + return a + return a - m + + +def crt(m, v, symmetric=False, check=True): + r"""Chinese Remainder Theorem. + + The moduli in m are assumed to be pairwise coprime. The output + is then an integer f, such that f = v_i mod m_i for each pair out + of v and m. If ``symmetric`` is False a positive integer will be + returned, else \|f\| will be less than or equal to the LCM of the + moduli, and thus f may be negative. + + If the moduli are not co-prime the correct result will be returned + if/when the test of the result is found to be incorrect. This result + will be None if there is no solution. + + The keyword ``check`` can be set to False if it is known that the moduli + are coprime. + + Examples + ======== + + As an example consider a set of residues ``U = [49, 76, 65]`` + and a set of moduli ``M = [99, 97, 95]``. Then we have:: + + >>> from sympy.ntheory.modular import crt + + >>> crt([99, 97, 95], [49, 76, 65]) + (639985, 912285) + + This is the correct result because:: + + >>> [639985 % m for m in [99, 97, 95]] + [49, 76, 65] + + If the moduli are not co-prime, you may receive an incorrect result + if you use ``check=False``: + + >>> crt([12, 6, 17], [3, 4, 2], check=False) + (954, 1224) + >>> [954 % m for m in [12, 6, 17]] + [6, 0, 2] + >>> crt([12, 6, 17], [3, 4, 2]) is None + True + >>> crt([3, 6], [2, 5]) + (5, 6) + + Note: the order of gf_crt's arguments is reversed relative to crt, + and that solve_congruence takes residue, modulus pairs. + + Programmer's note: rather than checking that all pairs of moduli share + no GCD (an O(n**2) test) and rather than factoring all moduli and seeing + that there is no factor in common, a check that the result gives the + indicated residuals is performed -- an O(n) operation. + + See Also + ======== + + solve_congruence + sympy.polys.galoistools.gf_crt : low level crt routine used by this routine + """ + if check: + m = list(map(as_int, m)) + v = list(map(as_int, v)) + + result = gf_crt(v, m, ZZ) + mm = prod(m) + + if check: + if not all(v % m == result % m for v, m in zip(v, m)): + result = solve_congruence(*list(zip(v, m)), + check=False, symmetric=symmetric) + if result is None: + return result + result, mm = result + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def crt1(m): + """First part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1 + >>> crt1([18, 42, 6]) + (4536, [252, 108, 756], [0, 2, 0]) + """ + + return gf_crt1(m, ZZ) + + +def crt2(m, v, mm, e, s, symmetric=False): + """Second part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1, crt2 + >>> mm, e, s = crt1([18, 42, 6]) + >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s) + (0, 4536) + """ + + result = gf_crt2(v, m, mm, e, s, ZZ) + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def solve_congruence(*remainder_modulus_pairs, **hint): + """Compute the integer ``n`` that has the residual ``ai`` when it is + divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to + this function: ((a1, m1), (a2, m2), ...). If there is no solution, + return None. Otherwise return ``n`` and its modulus. + + The ``mi`` values need not be co-prime. If it is known that the moduli are + not co-prime then the hint ``check`` can be set to False (default=True) and + the check for a quicker solution via crt() (valid when the moduli are + co-prime) will be skipped. + + If the hint ``symmetric`` is True (default is False), the value of ``n`` + will be within 1/2 of the modulus, possibly negative. + + Examples + ======== + + >>> from sympy.ntheory.modular import solve_congruence + + What number is 2 mod 3, 3 mod 5 and 2 mod 7? + + >>> solve_congruence((2, 3), (3, 5), (2, 7)) + (23, 105) + >>> [23 % m for m in [3, 5, 7]] + [2, 3, 2] + + If you prefer to work with all remainder in one list and + all moduli in another, send the arguments like this: + + >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7))) + (23, 105) + + The moduli need not be co-prime; in this case there may or + may not be a solution: + + >>> solve_congruence((2, 3), (4, 6)) is None + True + + >>> solve_congruence((2, 3), (5, 6)) + (5, 6) + + The symmetric flag will make the result be within 1/2 of the modulus: + + >>> solve_congruence((2, 3), (5, 6), symmetric=True) + (-1, 6) + + See Also + ======== + + crt : high level routine implementing the Chinese Remainder Theorem + + """ + def combine(c1, c2): + """Return the tuple (a, m) which satisfies the requirement + that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution + """ + a1, m1 = c1 + a2, m2 = c2 + a, b, c = m1, a2 - a1, m2 + g = reduce(igcd, [a, b, c]) + a, b, c = [i//g for i in [a, b, c]] + if a != 1: + inv_a, _, g = igcdex(a, c) + if g != 1: + return None + b *= inv_a + a, m = a1 + m1*b, m1*c + return a, m + + rm = remainder_modulus_pairs + symmetric = hint.get('symmetric', False) + + if hint.get('check', True): + rm = [(as_int(r), as_int(m)) for r, m in rm] + + # ignore redundant pairs but raise an error otherwise; also + # make sure that a unique set of bases is sent to gf_crt if + # they are all prime. + # + # The routine will work out less-trivial violations and + # return None, e.g. for the pairs (1,3) and (14,42) there + # is no answer because 14 mod 42 (having a gcd of 14) implies + # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14) + # which, being 0 mod 3, is inconsistent with 1 mod 3. But to + # preprocess the input beyond checking of another pair with 42 + # or 3 as the modulus (for this example) is not necessary. + uniq = {} + for r, m in rm: + r %= m + if m in uniq: + if r != uniq[m]: + return None + continue + uniq[m] = r + rm = [(r, m) for m, r in uniq.items()] + del uniq + + # if the moduli are co-prime, the crt will be significantly faster; + # checking all pairs for being co-prime gets to be slow but a prime + # test is a good trade-off + if all(isprime(m) for r, m in rm): + r, m = list(zip(*rm)) + return crt(m, r, symmetric=symmetric, check=False) + + rv = (0, 1) + for rmi in rm: + rv = combine(rv, rmi) + if rv is None: + break + n, m = rv + n = n % m + else: + if symmetric: + return symmetric_residue(n, m), m + return n, m diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/primetest.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/primetest.py new file mode 100644 index 0000000000000000000000000000000000000000..1872ef6307ee705b0642cdf28d3deec8d8ca4148 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/primetest.py @@ -0,0 +1,696 @@ +""" +Primality testing + +""" + +from sympy.core.numbers import igcd +from sympy.core.power import integer_nthroot +from sympy.core.sympify import sympify +from sympy.external.gmpy import HAS_GMPY +from sympy.utilities.misc import as_int + +from mpmath.libmp import bitcount as _bitlength + + +def _int_tuple(*i): + return tuple(int(_) for _ in i) + + +def is_euler_pseudoprime(n, b): + """Returns True if n is prime or an Euler pseudoprime to base b, else False. + + Euler Pseudoprime : In arithmetic, an odd composite integer n is called an + euler pseudoprime to base a, if a and n are coprime and satisfy the modular + arithmetic congruence relation : + + a ^ (n-1)/2 = + 1(mod n) or + a ^ (n-1)/2 = - 1(mod n) + + (where mod refers to the modulo operation). + + Examples + ======== + + >>> from sympy.ntheory.primetest import is_euler_pseudoprime + >>> is_euler_pseudoprime(2, 5) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime + """ + from sympy.ntheory.factor_ import trailing + + if not mr(n, [b]): + return False + + n = as_int(n) + r = n - 1 + c = pow(b, r >> trailing(r), n) + + if c == 1: + return True + + while True: + if c == n - 1: + return True + c = pow(c, 2, n) + if c == 1: + return False + + +def is_square(n, prep=True): + """Return True if n == a * a for some integer a, else False. + If n is suspected of *not* being a square then this is a + quick method of confirming that it is not. + + Examples + ======== + + >>> from sympy.ntheory.primetest import is_square + >>> is_square(25) + True + >>> is_square(2) + False + + References + ========== + + .. [1] https://mersenneforum.org/showpost.php?p=110896 + + See Also + ======== + sympy.core.power.integer_nthroot + """ + if prep: + n = as_int(n) + if n < 0: + return False + if n in (0, 1): + return True + # def magic(n): + # s = {x**2 % n for x in range(n)} + # return sum(1 << bit for bit in s) + # >>> print(hex(magic(128))) + # 0x2020212020202130202021202030213 + # >>> print(hex(magic(99))) + # 0x209060049048220348a410213 + # >>> print(hex(magic(91))) + # 0x102e403012a0c9862c14213 + # >>> print(hex(magic(85))) + # 0x121065188e001c46298213 + if not 0x2020212020202130202021202030213 & (1 << (n & 127)): + return False # e.g. 2, 3 + m = n % (99 * 91 * 85) + if not 0x209060049048220348a410213 & (1 << (m % 99)): + return False # e.g. 17, 68 + if not 0x102e403012a0c9862c14213 & (1 << (m % 91)): + return False # e.g. 97, 388 + if not 0x121065188e001c46298213 & (1 << (m % 85)): + return False # e.g. 793, 1408 + # n is either: + # a) odd = 4*even + 1 (and square if even = k*(k + 1)) + # b) even with + # odd multiplicity of 2 --> not square, e.g. 39040 + # even multiplicity of 2, e.g. 4, 16, 36, ..., 16324 + # removal of factors of 2 to give an odd, and rejection if + # any(i%2 for i in divmod(odd - 1, 4)) + # will give an odd number in form 4*even + 1. + # Use of `trailing` to check the power of 2 is not done since it + # does not apply to a large percentage of arbitrary numbers + # and the integer_nthroot is able to quickly resolve these cases. + return integer_nthroot(n, 2)[1] + + +def _test(n, base, s, t): + """Miller-Rabin strong pseudoprime test for one base. + Return False if n is definitely composite, True if n is + probably prime, with a probability greater than 3/4. + + """ + # do the Fermat test + b = pow(base, t, n) + if b == 1 or b == n - 1: + return True + else: + for j in range(1, s): + b = pow(b, 2, n) + if b == n - 1: + return True + # see I. Niven et al. "An Introduction to Theory of Numbers", page 78 + if b == 1: + return False + return False + + +def mr(n, bases): + """Perform a Miller-Rabin strong pseudoprime test on n using a + given list of bases/witnesses. + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 135-138 + + A list of thresholds and the bases they require are here: + https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants + + Examples + ======== + + >>> from sympy.ntheory.primetest import mr + >>> mr(1373651, [2, 3]) + False + >>> mr(479001599, [31, 73]) + True + + """ + from sympy.ntheory.factor_ import trailing + from sympy.polys.domains import ZZ + + n = as_int(n) + if n < 2: + return False + # remove powers of 2 from n-1 (= t * 2**s) + s = trailing(n - 1) + t = n >> s + for base in bases: + # Bases >= n are wrapped, bases < 2 are invalid + if base >= n: + base %= n + if base >= 2: + base = ZZ(base) + if not _test(n, base, s, t): + return False + return True + + +def _lucas_sequence(n, P, Q, k): + """Return the modular Lucas sequence (U_k, V_k, Q_k). + + Given a Lucas sequence defined by P, Q, returns the kth values for + U and V, along with Q^k, all modulo n. This is intended for use with + possibly very large values of n and k, where the combinatorial functions + would be completely unusable. + + The modular Lucas sequences are used in numerous places in number theory, + especially in the Lucas compositeness tests and the various n + 1 proofs. + + Examples + ======== + + >>> from sympy.ntheory.primetest import _lucas_sequence + >>> N = 10**2000 + 4561 + >>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol + (0, 2, 1) + + """ + D = P*P - 4*Q + if n < 2: + raise ValueError("n must be >= 2") + if k < 0: + raise ValueError("k must be >= 0") + if D == 0: + raise ValueError("D must not be zero") + + if k == 0: + return _int_tuple(0, 2, Q) + U = 1 + V = P + Qk = Q + b = _bitlength(k) + if Q == 1: + # Optimization for extra strong tests. + while b > 1: + U = (U*V) % n + V = (V*V - 2) % n + b -= 1 + if (k >> (b - 1)) & 1: + U, V = U*P + V, V*P + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + elif P == 1 and Q == -1: + # Small optimization for 50% of Selfridge parameters. + while b > 1: + U = (U*V) % n + if Qk == 1: + V = (V*V - 2) % n + else: + V = (V*V + 2) % n + Qk = 1 + b -= 1 + if (k >> (b-1)) & 1: + U, V = U + V, V + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + Qk = -1 + else: + # The general case with any P and Q. + while b > 1: + U = (U*V) % n + V = (V*V - 2*Qk) % n + Qk *= Qk + b -= 1 + if (k >> (b - 1)) & 1: + U, V = U*P + V, V*P + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + Qk *= Q + Qk %= n + return _int_tuple(U % n, V % n, Qk) + + +def _lucas_selfridge_params(n): + """Calculates the Selfridge parameters (D, P, Q) for n. This is + method A from page 1401 of Baillie and Wagstaff. + + References + ========== + .. [1] "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + """ + from sympy.ntheory.residue_ntheory import jacobi_symbol + D = 5 + while True: + g = igcd(abs(D), n) + if g > 1 and g != n: + return (0, 0, 0) + if jacobi_symbol(D, n) == -1: + break + if D > 0: + D = -D - 2 + else: + D = -D + 2 + return _int_tuple(D, 1, (1 - D)/4) + + +def _lucas_extrastrong_params(n): + """Calculates the "extra strong" parameters (D, P, Q) for n. + + References + ========== + .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes + https://oeis.org/A217719 + .. [1] https://en.wikipedia.org/wiki/Lucas_pseudoprime + """ + from sympy.ntheory.residue_ntheory import jacobi_symbol + P, Q, D = 3, 1, 5 + while True: + g = igcd(D, n) + if g > 1 and g != n: + return (0, 0, 0) + if jacobi_symbol(D, n) == -1: + break + P += 1 + D = P*P - 4 + return _int_tuple(D, P, Q) + + +def is_lucas_prp(n): + """Standard Lucas compositeness test with Selfridge parameters. Returns + False if n is definitely composite, and True if n is a Lucas probable + prime. + + This is typically used in combination with the Miller-Rabin test. + + References + ========== + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - OEIS A217120: Lucas Pseudoprimes + https://oeis.org/A217120 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_lucas_prp + >>> for i in range(10000): + ... if is_lucas_prp(i) and not isprime(i): + ... print(i) + 323 + 377 + 1159 + 1829 + 3827 + 5459 + 5777 + 9071 + 9179 + """ + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_selfridge_params(n) + if D == 0: + return False + U, V, Qk = _lucas_sequence(n, P, Q, n+1) + return U == 0 + + +def is_strong_lucas_prp(n): + """Strong Lucas compositeness test with Selfridge parameters. Returns + False if n is definitely composite, and True if n is a strong Lucas + probable prime. + + This is often used in combination with the Miller-Rabin test, and + in particular, when combined with M-R base 2 creates the strong BPSW test. + + References + ========== + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - OEIS A217255: Strong Lucas Pseudoprimes + https://oeis.org/A217255 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp + >>> for i in range(20000): + ... if is_strong_lucas_prp(i) and not isprime(i): + ... print(i) + 5459 + 5777 + 10877 + 16109 + 18971 + """ + from sympy.ntheory.factor_ import trailing + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_selfridge_params(n) + if D == 0: + return False + + # remove powers of 2 from n+1 (= k * 2**s) + s = trailing(n + 1) + k = (n+1) >> s + + U, V, Qk = _lucas_sequence(n, P, Q, k) + + if U == 0 or V == 0: + return True + for r in range(1, s): + V = (V*V - 2*Qk) % n + if V == 0: + return True + Qk = pow(Qk, 2, n) + return False + + +def is_extra_strong_lucas_prp(n): + """Extra Strong Lucas compositeness test. Returns False if n is + definitely composite, and True if n is a "extra strong" Lucas probable + prime. + + The parameters are selected using P = 3, Q = 1, then incrementing P until + (D|n) == -1. The test itself is as defined in Grantham 2000, from the + Mo and Jones preprint. The parameter selection and test are the same as + used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime + page on Wikipedia. + + With these parameters, there are no counterexamples below 2^64 nor any + known above that range. It is 20-50% faster than the strong test. + + Because of the different parameters selected, there is no relationship + between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes. + In particular, one is not a subset of the other. + + References + ========== + - "Frobenius Pseudoprimes", Jon Grantham, 2000. + https://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/ + - OEIS A217719: Extra Strong Lucas Pseudoprimes + https://oeis.org/A217719 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp + >>> for i in range(20000): + ... if is_extra_strong_lucas_prp(i) and not isprime(i): + ... print(i) + 989 + 3239 + 5777 + 10877 + """ + # Implementation notes: + # 1) the parameters differ from Thomas R. Nicely's. His parameter + # selection leads to pseudoprimes that overlap M-R tests, and + # contradict Baillie and Wagstaff's suggestion of (D|n) = -1. + # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas + # sequence must have Q=1. See Grantham theorem 2.3, any of the + # references on the MathWorld page, or run it and see Q=-1 is wrong. + from sympy.ntheory.factor_ import trailing + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_extrastrong_params(n) + if D == 0: + return False + + # remove powers of 2 from n+1 (= k * 2**s) + s = trailing(n + 1) + k = (n+1) >> s + + U, V, Qk = _lucas_sequence(n, P, Q, k) + + if U == 0 and (V == 2 or V == n - 2): + return True + for r in range(1, s): + if V == 0: + return True + V = (V*V - 2) % n + return False + + +def isprime(n): + """ + Test if n is a prime number (True) or not (False). For n < 2^64 the + answer is definitive; larger n values have a small probability of actually + being pseudoprimes. + + Negative numbers (e.g. -2) are not considered prime. + + The first step is looking for trivial factors, which if found enables + a quick return. Next, if the sieve is large enough, use bisection search + on the sieve. For small numbers, a set of deterministic Miller-Rabin + tests are performed with bases that are known to have no counterexamples + in their range. Finally if the number is larger than 2^64, a strong + BPSW test is performed. While this is a probable prime test and we + believe counterexamples exist, there are no known counterexamples. + + Examples + ======== + + >>> from sympy.ntheory import isprime + >>> isprime(13) + True + >>> isprime(13.0) # limited precision + False + >>> isprime(15) + False + + Notes + ===== + + This routine is intended only for integer input, not numerical + expressions which may represent numbers. Floats are also + rejected as input because they represent numbers of limited + precision. While it is tempting to permit 7.0 to represent an + integer there are errors that may "pass silently" if this is + allowed: + + >>> from sympy import Float, S + >>> int(1e3) == 1e3 == 10**3 + True + >>> int(1e23) == 1e23 + True + >>> int(1e23) == 10**23 + False + + >>> near_int = 1 + S(1)/10**19 + >>> near_int == int(near_int) + False + >>> n = Float(near_int, 10) # truncated by precision + >>> n == int(n) + True + >>> n = Float(near_int, 20) + >>> n == int(n) + False + + See Also + ======== + + sympy.ntheory.generate.primerange : Generates all primes in a given range + sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n + sympy.ntheory.generate.prime : Return the nth prime + + References + ========== + - https://en.wikipedia.org/wiki/Strong_pseudoprime + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test + """ + try: + n = as_int(n) + except ValueError: + return False + + # Step 1, do quick composite testing via trial division. The individual + # modulo tests benchmark faster than one or two primorial igcds for me. + # The point here is just to speedily handle small numbers and many + # composites. Step 2 only requires that n <= 2 get handled here. + if n in [2, 3, 5]: + return True + if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0: + return False + if n < 49: + return True + if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \ + (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \ + (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0: + return False + if n < 2809: + return True + if n < 31417: + return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951, 23377] + + # bisection search on the sieve if the sieve is large enough + from sympy.ntheory.generate import sieve as s + if n <= s._list[-1]: + l, u = s.search(n) + return l == u + + # If we have GMPY2, skip straight to step 3 and do a strong BPSW test. + # This should be a bit faster than our step 2, and for large values will + # be a lot faster than our step 3 (C+GMP vs. Python). + if HAS_GMPY == 2: + from gmpy2 import is_strong_prp, is_strong_selfridge_prp + return is_strong_prp(n, 2) and is_strong_selfridge_prp(n) + + + # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See: + # https://miller-rabin.appspot.com/ + # for lists. We have made sure the M-R routine will successfully handle + # bases larger than n, so we can use the minimal set. + # In September 2015 deterministic numbers were extended to over 2^81. + # https://arxiv.org/pdf/1509.00864.pdf + # https://oeis.org/A014233 + if n < 341531: + return mr(n, [9345883071009581737]) + if n < 885594169: + return mr(n, [725270293939359937, 3569819667048198375]) + if n < 350269456337: + return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375]) + if n < 55245642489451: + return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650]) + if n < 7999252175582851: + return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805]) + if n < 585226005592931977: + return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375]) + if n < 18446744073709551616: + return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) + if n < 318665857834031151167461: + return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]) + if n < 3317044064679887385961981: + return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]) + + # We could do this instead at any point: + #if n < 18446744073709551616: + # return mr(n, [2]) and is_extra_strong_lucas_prp(n) + + # Here are tests that are safe for MR routines that don't understand + # large bases. + #if n < 9080191: + # return mr(n, [31, 73]) + #if n < 19471033: + # return mr(n, [2, 299417]) + #if n < 38010307: + # return mr(n, [2, 9332593]) + #if n < 316349281: + # return mr(n, [11000544, 31481107]) + #if n < 4759123141: + # return mr(n, [2, 7, 61]) + #if n < 105936894253: + # return mr(n, [2, 1005905886, 1340600841]) + #if n < 31858317218647: + # return mr(n, [2, 642735, 553174392, 3046413974]) + #if n < 3071837692357849: + # return mr(n, [2, 75088, 642735, 203659041, 3613982119]) + #if n < 18446744073709551616: + # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) + + # Step 3: BPSW. + # + # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed + # 44.0s old isprime using 46 bases + # 5.3s strong BPSW + one random base + # 4.3s extra strong BPSW + one random base + # 4.1s strong BPSW + # 3.2s extra strong BPSW + + # Classic BPSW from page 1401 of the paper. See alternate ideas below. + return mr(n, [2]) and is_strong_lucas_prp(n) + + # Using extra strong test, which is somewhat faster + #return mr(n, [2]) and is_extra_strong_lucas_prp(n) + + # Add a random M-R base + #import random + #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n) + + +def is_gaussian_prime(num): + r"""Test if num is a Gaussian prime number. + + References + ========== + + .. [1] https://oeis.org/wiki/Gaussian_primes + """ + + num = sympify(num) + a, b = num.as_real_imag() + a = as_int(a, strict=False) + b = as_int(b, strict=False) + if a == 0: + b = abs(b) + return isprime(b) and b % 4 == 3 + elif b == 0: + a = abs(a) + return isprime(a) and a % 4 == 3 + return isprime(a**2 + b**2) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/qs.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/qs.py new file mode 100644 index 0000000000000000000000000000000000000000..993a8e33fe8aa588f9953970a6f238ad3b7d363b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/qs.py @@ -0,0 +1,515 @@ +from sympy.core.numbers import igcd, mod_inverse +from sympy.core.power import integer_nthroot +from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power +from sympy.ntheory import isprime +from math import log, sqrt +import random + +rgen = random.Random() + +class SievePolynomial: + def __init__(self, modified_coeff=(), a=None, b=None): + """This class denotes the seive polynomial. + If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded + to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient + is stored in the form `[a**2, 2*a*b, b**2 - N]`. This + ensures faster `eval` method because we dont have to + perform `a**2, 2*a*b, b**2` every time we call the + `eval` method. As multiplication is more expensive + than addition, by using modified_coefficient we get + a faster seiving process. + + Parameters + ========== + + modified_coeff : modified_coefficient of sieve polynomial + a : parameter of the sieve polynomial + b : parameter of the sieve polynomial + """ + self.modified_coeff = modified_coeff + self.a = a + self.b = b + + def eval(self, x): + """ + Compute the value of the sieve polynomial at point x. + + Parameters + ========== + + x : Integer parameter for sieve polynomial + """ + ans = 0 + for coeff in self.modified_coeff: + ans *= x + ans += coeff + return ans + + +class FactorBaseElem: + """This class stores an element of the `factor_base`. + """ + def __init__(self, prime, tmem_p, log_p): + """ + Initialization of factor_base_elem. + + Parameters + ========== + + prime : prime number of the factor_base + tmem_p : Integer square root of x**2 = n mod prime + log_p : Compute Natural Logarithm of the prime + """ + self.prime = prime + self.tmem_p = tmem_p + self.log_p = log_p + self.soln1 = None + self.soln2 = None + self.a_inv = None + self.b_ainv = None + + +def _generate_factor_base(prime_bound, n): + """Generate `factor_base` for Quadratic Sieve. The `factor_base` + consists of all the points whose ``legendre_symbol(n, p) == 1`` + and ``p < num_primes``. Along with the prime `factor_base` also stores + natural logarithm of prime and the residue n modulo p. + It also returns the of primes numbers in the `factor_base` which are + close to 1000 and 5000. + + Parameters + ========== + + prime_bound : upper prime bound of the factor_base + n : integer to be factored + """ + from sympy.ntheory.generate import sieve + factor_base = [] + idx_1000, idx_5000 = None, None + for prime in sieve.primerange(1, prime_bound): + if pow(n, (prime - 1) // 2, prime) == 1: + if prime > 1000 and idx_1000 is None: + idx_1000 = len(factor_base) - 1 + if prime > 5000 and idx_5000 is None: + idx_5000 = len(factor_base) - 1 + residue = _sqrt_mod_prime_power(n, prime, 1)[0] + log_p = round(log(prime)*2**10) + factor_base.append(FactorBaseElem(prime, residue, log_p)) + return idx_1000, idx_5000, factor_base + + +def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None): + """This step is the initialization of the 1st sieve polynomial. + Here `a` is selected as a product of several primes of the factor_base + such that `a` is about to ``sqrt(2*N) / M``. Other initial values of + factor_base elem are also initialized which includes a_inv, b_ainv, soln1, + soln2 which are used when the sieve polynomial is changed. The b_ainv + is required for fast polynomial change as we do not have to calculate + `2*b*mod_inverse(a, prime)` every time. + We also ensure that the `factor_base` primes which make `a` are between + 1000 and 5000. + + Parameters + ========== + + N : Number to be factored + M : sieve interval + factor_base : factor_base primes + idx_1000 : index of prime number in the factor_base near 1000 + idx_5000 : index of prime number in the factor_base near to 5000 + seed : Generate pseudoprime numbers + """ + if seed is not None: + rgen.seed(seed) + approx_val = sqrt(2*N) / M + # `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a` + # randomly search for a combination of primes whose multiplication is close to approx_val + # This multiplication of primes will be `a` and the primes will be `q` + # `best_a` denotes that `a` is close to approx_val in the random search of combination + best_a, best_q, best_ratio = None, None, None + start = 0 if idx_1000 is None else idx_1000 + end = len(factor_base) - 1 if idx_5000 is None else idx_5000 + for _ in range(50): + a = 1 + q = [] + while(a < approx_val): + rand_p = 0 + while(rand_p == 0 or rand_p in q): + rand_p = rgen.randint(start, end) + p = factor_base[rand_p].prime + a *= p + q.append(rand_p) + ratio = a / approx_val + if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1): + best_q = q + best_a = a + best_ratio = ratio + + a = best_a + q = best_q + + B = [] + for idx, val in enumerate(q): + q_l = factor_base[val].prime + gamma = factor_base[val].tmem_p * mod_inverse(a // q_l, q_l) % q_l + if gamma > q_l / 2: + gamma = q_l - gamma + B.append(a//q_l*gamma) + + b = sum(B) + g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) + + for fb in factor_base: + if a % fb.prime == 0: + continue + fb.a_inv = mod_inverse(a, fb.prime) + fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B] + fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime + fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime + return g, B + + +def _initialize_ith_poly(N, factor_base, i, g, B): + """Initialization stage of ith poly. After we finish sieving 1`st polynomial + here we quickly change to the next polynomial from which we will again + start sieving. Suppose we generated ith sieve polynomial and now we + want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1`` + where `j` is the number of prime factors of the coefficient `a` + then this function can be used to go to the next polynomial. If + ``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage. + + Parameters + ========== + + N : number to be factored + factor_base : factor_base primes + i : integer denoting ith polynomial + g : (i - 1)th polynomial + B : array that stores a//q_l*gamma + """ + from sympy.functions.elementary.integers import ceiling + v = 1 + j = i + while(j % 2 == 0): + v += 1 + j //= 2 + if ceiling(i / (2**v)) % 2 == 1: + neg_pow = -1 + else: + neg_pow = 1 + b = g.b + 2*neg_pow*B[v - 1] + a = g.a + g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) + for fb in factor_base: + if a % fb.prime == 0: + continue + fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime + fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime + + return g + + +def _gen_sieve_array(M, factor_base): + """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base + that does not divide the coefficient `a` we add log_p over the sieve_array + such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i` + is an integer. When p = 2 then log_p is only added using + ``-M <= soln1 + i*p <= M``. + + Parameters + ========== + + M : sieve interval + factor_base : factor_base primes + """ + sieve_array = [0]*(2*M + 1) + for factor in factor_base: + if factor.soln1 is None: #The prime does not divides a + continue + for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime): + sieve_array[idx] += factor.log_p + if factor.prime == 2: + continue + #if prime is 2 then sieve only with soln_1_p + for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime): + sieve_array[idx] += factor.log_p + return sieve_array + + +def _check_smoothness(num, factor_base): + """Here we check that if `num` is a smooth number or not. If `a` is a smooth + number then it returns a vector of prime exponents modulo 2. For example + if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then + `a` is a smooth number and this function returns ([1, 0, 0, 1], True). If + `a` is a partial relation which means that `a` a has one prime factor + greater than the `factor_base` then it returns `(a, False)` which denotes `a` + is a partial relation. + + Parameters + ========== + + a : integer whose smootheness is to be checked + factor_base : factor_base primes + """ + vec = [] + if num < 0: + vec.append(1) + num *= -1 + else: + vec.append(0) + #-1 is not included in factor_base add -1 in vector + for factor in factor_base: + if num % factor.prime != 0: + vec.append(0) + continue + factor_exp = 0 + while num % factor.prime == 0: + factor_exp += 1 + num //= factor.prime + vec.append(factor_exp % 2) + if num == 1: + return vec, True + if isprime(num): + return num, False + return None, None + + +def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM): + """Trial division stage. Here we trial divide the values generetated + by sieve_poly in the sieve interval and if it is a smooth number then + it is stored in `smooth_relations`. Moreover, if we find two partial relations + with same large prime then they are combined to form a smooth relation. + First we iterate over sieve array and look for values which are greater + than accumulated_val, as these values have a high chance of being smooth + number. Then using these values we find smooth relations. + In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations + with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN`` + to form a smooth relation. + + Parameters + ========== + + N : Number to be factored + M : sieve interval + factor_base : factor_base primes + sieve_array : stores log_p values + sieve_poly : polynomial from which we find smooth relations + partial_relations : stores partial relations with one large prime + ERROR_TERM : error term for accumulated_val + """ + sqrt_n = sqrt(float(N)) + accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM + smooth_relations = [] + proper_factor = set() + partial_relation_upper_bound = 128*factor_base[-1].prime + for idx, val in enumerate(sieve_array): + if val < accumulated_val: + continue + x = idx - M + v = sieve_poly.eval(x) + vec, is_smooth = _check_smoothness(v, factor_base) + if is_smooth is None:#Neither smooth nor partial + continue + u = sieve_poly.a*x + sieve_poly.b + # Update the partial relation + # If 2 partial relation with same large prime is found then generate smooth relation + if is_smooth is False:#partial relation found + large_prime = vec + #Consider the large_primes under 128*F + if large_prime > partial_relation_upper_bound: + continue + if large_prime not in partial_relations: + partial_relations[large_prime] = (u, v) + continue + else: + u_prev, v_prev = partial_relations[large_prime] + partial_relations.pop(large_prime) + try: + large_prime_inv = mod_inverse(large_prime, N) + except ValueError:#if large_prine divides N + proper_factor.add(large_prime) + continue + u = u*u_prev*large_prime_inv + v = v*v_prev // (large_prime*large_prime) + vec, is_smooth = _check_smoothness(v, factor_base) + #assert u*u % N == v % N + smooth_relations.append((u, v, vec)) + return smooth_relations, proper_factor + + +#LINEAR ALGEBRA STAGE +def _build_matrix(smooth_relations): + """Build a 2D matrix from smooth relations. + + Parameters + ========== + + smooth_relations : Stores smooth relations + """ + matrix = [] + for s_relation in smooth_relations: + matrix.append(s_relation[2]) + return matrix + + +def _gauss_mod_2(A): + """Fast gaussian reduction for modulo 2 matrix. + + Parameters + ========== + + A : Matrix + + Examples + ======== + + >>> from sympy.ntheory.qs import _gauss_mod_2 + >>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]]) + ([[[1, 0, 1], 3]], + [True, True, True, False], + [[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]]) + + Reference + ========== + + .. [1] A fast algorithm for gaussian elimination over GF(2) and + its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige""" + import copy + matrix = copy.deepcopy(A) + row = len(matrix) + col = len(matrix[0]) + mark = [False]*row + for c in range(col): + for r in range(row): + if matrix[r][c] == 1: + break + mark[r] = True + for c1 in range(col): + if c1 == c: + continue + if matrix[r][c1] == 1: + for r2 in range(row): + matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2 + dependent_row = [] + for idx, val in enumerate(mark): + if val == False: + dependent_row.append([matrix[idx], idx]) + return dependent_row, mark, matrix + + +def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N): + """Finds proper factor of N. Here, transform the dependent rows as a + combination of independent rows of the gauss_matrix to form the desired + relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation + we obtain a proper factor of N by `gcd(X - Y, N)`. + + Parameters + ========== + + dependent_rows : denoted dependent rows in the reduced matrix form + mark : boolean array to denoted dependent and independent rows + gauss_matrix : Reduced form of the smooth relations matrix + index : denoted the index of the dependent_rows + smooth_relations : Smooth relations vectors matrix + N : Number to be factored + """ + idx_in_smooth = dependent_rows[index][1] + independent_u = [smooth_relations[idx_in_smooth][0]] + independent_v = [smooth_relations[idx_in_smooth][1]] + dept_row = dependent_rows[index][0] + + for idx, val in enumerate(dept_row): + if val == 1: + for row in range(len(gauss_matrix)): + if gauss_matrix[row][idx] == 1 and mark[row] == True: + independent_u.append(smooth_relations[row][0]) + independent_v.append(smooth_relations[row][1]) + break + + u = 1 + v = 1 + for i in independent_u: + u *= i + for i in independent_v: + v *= i + #assert u**2 % N == v % N + v = integer_nthroot(v, 2)[0] + return igcd(u - v, N) + + +def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234): + """Performs factorization using Self-Initializing Quadratic Sieve. + In SIQS, let N be a number to be factored, and this N should not be a + perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and + ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N. + In order to find these integers X and Y we try to find relations of form + t**2 = u modN where u is a product of small primes. If we have enough of + these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that + the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``. + + Here, several optimizations are done like using multiple polynomials for + sieving, fast changing between polynomials and using partial relations. + The use of partial relations can speeds up the factoring by 2 times. + + Parameters + ========== + + N : Number to be Factored + prime_bound : upper bound for primes in the factor base + M : Sieve Interval + ERROR_TERM : Error term for checking smoothness + threshold : Extra smooth relations for factorization + seed : generate pseudo prime numbers + + Examples + ======== + + >>> from sympy.ntheory import qs + >>> qs(25645121643901801, 2000, 10000) + {5394769, 4753701529} + >>> qs(9804659461513846513, 2000, 10000) + {4641991, 2112166839943} + + References + ========== + + .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf + .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve + """ + ERROR_TERM*=2**10 + rgen.seed(seed) + idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N) + smooth_relations = [] + ith_poly = 0 + partial_relations = {} + proper_factor = set() + threshold = 5*len(factor_base) // 100 + while True: + if ith_poly == 0: + ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000) + else: + ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array) + ith_poly += 1 + if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial + ith_poly = 0 + sieve_array = _gen_sieve_array(M, factor_base) + s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM) + smooth_relations += s_rel + proper_factor |= p_f + if len(smooth_relations) >= len(factor_base) + threshold: + break + matrix = _build_matrix(smooth_relations) + dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) + N_copy = N + for index in range(len(dependent_row)): + factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N) + if factor > 1 and factor < N: + proper_factor.add(factor) + while(N_copy % factor == 0): + N_copy //= factor + if isprime(N_copy): + proper_factor.add(N_copy) + break + if(N_copy == 1): + break + return proper_factor diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..cba4735556cccc6cd1842877f6ec63a1e693c686 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py @@ -0,0 +1,1573 @@ +from __future__ import annotations + +from sympy.core.function import Function +from sympy.core.numbers import igcd, igcdex, mod_inverse +from sympy.core.power import isqrt +from sympy.core.singleton import S +from sympy.polys import Poly +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence +from .primetest import isprime +from .factor_ import factorint, trailing, totient, multiplicity, perfect_power +from sympy.utilities.misc import as_int +from sympy.core.random import _randint, randint + +from itertools import cycle, product + + +def n_order(a, n): + """Returns the order of ``a`` modulo ``n``. + + The order of ``a`` modulo ``n`` is the smallest integer + ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. + + Parameters + ========== + + a : integer + n : integer, n > 1. a and n should be relatively prime + + Examples + ======== + + >>> from sympy.ntheory import n_order + >>> n_order(3, 7) + 6 + >>> n_order(4, 7) + 3 + """ + from collections import defaultdict + a, n = as_int(a), as_int(n) + if n <= 1: + raise ValueError("n should be an integer greater than 1") + a = a % n + # Trivial + if a == 1: + return 1 + if igcd(a, n) != 1: + raise ValueError("The two numbers should be relatively prime") + # We want to calculate + # order = totient(n), factors = factorint(order) + factors = defaultdict(int) + for px, kx in factorint(n).items(): + if kx > 1: + factors[px] += kx - 1 + for py, ky in factorint(px - 1).items(): + factors[py] += ky + order = 1 + for px, kx in factors.items(): + order *= px**kx + # Now the `order` is the order of the group. + # The order of `a` divides the order of the group. + for p, e in factors.items(): + for _ in range(e): + if pow(a, order // p, n) == 1: + order //= p + else: + break + return order + + +def _primitive_root_prime_iter(p): + """ + Generates the primitive roots for a prime ``p`` + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter + >>> list(_primitive_root_prime_iter(19)) + [2, 3, 10, 13, 14, 15] + + References + ========== + + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 + + """ + # it is assumed that p is an int + v = [(p - 1) // i for i in factorint(p - 1).keys()] + a = 2 + while a < p: + for pw in v: + # a TypeError below may indicate that p was not an int + if pow(a, pw, p) == 1: + break + else: + yield a + a += 1 + + +def primitive_root(p): + """ + Returns the smallest primitive root or None. + + Parameters + ========== + + p : positive integer + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import primitive_root + >>> primitive_root(19) + 2 + + References + ========== + + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 + .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C + + """ + p = as_int(p) + if p < 1: + raise ValueError('p is required to be positive') + if p <= 2: + return 1 + f = factorint(p) + if len(f) > 2: + return None + if len(f) == 2: + if 2 not in f or f[2] > 1: + return None + + # case p = 2*p1**k, p1 prime + for p1, e1 in f.items(): + if p1 != 2: + break + i = 1 + while i < p: + i += 2 + if i % p1 == 0: + continue + if is_primitive_root(i, p): + return i + + else: + if 2 in f: + if p == 4: + return 3 + return None + p1, n = list(f.items())[0] + if n > 1: + # see Ref [2], page 81 + g = primitive_root(p1) + if is_primitive_root(g, p1**2): + return g + else: + for i in range(2, g + p1 + 1): + if igcd(i, p) == 1 and is_primitive_root(i, p): + return i + + return next(_primitive_root_prime_iter(p)) + + +def is_primitive_root(a, p): + """ + Returns True if ``a`` is a primitive root of ``p``. + + ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and + totient(p) is the smallest positive number s.t. + + a**totient(p) cong 1 mod(p) + + Parameters + ========== + + a : integer + p : integer, p > 1. a and p should be relatively prime + + Examples + ======== + + >>> from sympy.ntheory import is_primitive_root, n_order, totient + >>> is_primitive_root(3, 10) + True + >>> is_primitive_root(9, 10) + False + >>> n_order(3, 10) == totient(10) + True + >>> n_order(9, 10) == totient(10) + False + + """ + a, p = as_int(a), as_int(p) + if p <= 1: + raise ValueError("p should be an integer greater than 1") + a = a % p + if igcd(a, p) != 1: + raise ValueError("The two numbers should be relatively prime") + # Primitive root of p exist only for + # p = 2, 4, q**e, 2*q**e (q is odd prime) + if p <= 4: + # The primitive root is only p-1. + return a == p - 1 + t = trailing(p) + if t > 1: + return False + q = p >> t + if isprime(q): + group_order = q - 1 + factors = set(factorint(q - 1).keys()) + else: + m = perfect_power(q) + if not m: + return False + q, e = m + if not isprime(q): + return False + group_order = q**(e - 1)*(q - 1) + factors = set(factorint(q - 1).keys()) + factors.add(q) + return all(pow(a, group_order // prime, p) != 1 for prime in factors) + + +def _sqrt_mod_tonelli_shanks(a, p): + """ + Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` + + References + ========== + + .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 + + """ + s = trailing(p - 1) + t = p >> s + # find a non-quadratic residue + while 1: + d = randint(2, p - 1) + r = legendre_symbol(d, p) + if r == -1: + break + #assert legendre_symbol(d, p) == -1 + A = pow(a, t, p) + D = pow(d, t, p) + m = 0 + for i in range(s): + adm = A*pow(D, m, p) % p + adm = pow(adm, 2**(s - 1 - i), p) + if adm % p == p - 1: + m += 2**i + #assert A*pow(D, m, p) % p == 1 + x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p + return x + + +def sqrt_mod(a, p, all_roots=False): + """ + Find a root of ``x**2 = a mod p``. + + Parameters + ========== + + a : integer + p : positive integer + all_roots : if True the list of roots is returned or None + + Notes + ===== + + If there is no root it is returned None; else the returned root + is less or equal to ``p // 2``; in general is not the smallest one. + It is returned ``p // 2`` only if it is the only root. + + Use ``all_roots`` only when it is expected that all the roots fit + in memory; otherwise use ``sqrt_mod_iter``. + + Examples + ======== + + >>> from sympy.ntheory import sqrt_mod + >>> sqrt_mod(11, 43) + 21 + >>> sqrt_mod(17, 32, True) + [7, 9, 23, 25] + """ + if all_roots: + return sorted(sqrt_mod_iter(a, p)) + try: + p = abs(as_int(p)) + it = sqrt_mod_iter(a, p) + r = next(it) + if r > p // 2: + return p - r + elif r < p // 2: + return r + else: + try: + r = next(it) + if r > p // 2: + return p - r + except StopIteration: + pass + return r + except StopIteration: + return None + + +def _product(*iters): + """ + Cartesian product generator + + Notes + ===== + + Unlike itertools.product, it works also with iterables which do not fit + in memory. See https://bugs.python.org/issue10109 + + Author: Fernando Sumudu + with small changes + """ + inf_iters = tuple(cycle(enumerate(it)) for it in iters) + num_iters = len(inf_iters) + cur_val = [None]*num_iters + + first_v = True + while True: + i, p = 0, num_iters + while p and not i: + p -= 1 + i, cur_val[p] = next(inf_iters[p]) + + if not p and not i: + if first_v: + first_v = False + else: + break + + yield cur_val + + +def sqrt_mod_iter(a, p, domain=int): + """ + Iterate over solutions to ``x**2 = a mod p``. + + Parameters + ========== + + a : integer + p : positive integer + domain : integer domain, ``int``, ``ZZ`` or ``Integer`` + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter + >>> list(sqrt_mod_iter(11, 43)) + [21, 22] + """ + a, p = as_int(a), abs(as_int(p)) + if isprime(p): + a = a % p + if a == 0: + res = _sqrt_mod1(a, p, 1) + else: + res = _sqrt_mod_prime_power(a, p, 1) + if res: + if domain is ZZ: + yield from res + else: + for x in res: + yield domain(x) + else: + f = factorint(p) + v = [] + pv = [] + for px, ex in f.items(): + if a % px == 0: + rx = _sqrt_mod1(a, px, ex) + if not rx: + return + else: + rx = _sqrt_mod_prime_power(a, px, ex) + if not rx: + return + v.append(rx) + pv.append(px**ex) + mm, e, s = gf_crt1(pv, ZZ) + if domain is ZZ: + for vx in _product(*v): + r = gf_crt2(vx, pv, mm, e, s, ZZ) + yield r + else: + for vx in _product(*v): + r = gf_crt2(vx, pv, mm, e, s, ZZ) + yield domain(r) + + +def _sqrt_mod_prime_power(a, p, k): + """ + Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` + + Parameters + ========== + + a : integer + p : prime number + k : positive integer + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power + >>> _sqrt_mod_prime_power(11, 43, 1) + [21, 22] + + References + ========== + + .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 + .. [2] http://www.numbertheory.org/php/squareroot.html + .. [3] [Gathen99]_ + """ + pk = p**k + a = a % pk + + if k == 1: + if p == 2: + return [ZZ(a)] + if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1): + return None + + if p % 4 == 3: + res = pow(a, (p + 1) // 4, p) + elif p % 8 == 5: + sign = pow(a, (p - 1) // 4, p) + if sign == 1: + res = pow(a, (p + 3) // 8, p) + else: + b = pow(4*a, (p - 5) // 8, p) + x = (2*a*b) % p + if pow(x, 2, p) == a: + res = x + else: + res = _sqrt_mod_tonelli_shanks(a, p) + + # ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic; + # sort to get always the same result + return sorted([ZZ(res), ZZ(p - res)]) + + if k > 1: + # see Ref.[2] + if p == 2: + if a % 8 != 1: + return None + if k <= 3: + s = set() + for i in range(0, pk, 4): + s.add(1 + i) + s.add(-1 + i) + return list(s) + # according to Ref.[2] for k > 2 there are two solutions + # (mod 2**k-1), that is four solutions (mod 2**k), which can be + # obtained from the roots of x**2 = 0 (mod 8) + rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)] + # hensel lift them to solutions of x**2 = 0 (mod 2**k) + # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1) + # then r + 2**(nx - 1) is a root mod 2**(nx+1) + n = 3 + res = [] + for r in rv: + nx = n + while nx < k: + r1 = (r**2 - a) >> nx + if r1 % 2: + r = r + (1 << (nx - 1)) + #assert (r**2 - a)% (1 << (nx + 1)) == 0 + nx += 1 + if r not in res: + res.append(r) + x = r + (1 << (k - 1)) + #assert (x**2 - a) % pk == 0 + if x < (1 << nx) and x not in res: + if (x**2 - a) % pk == 0: + res.append(x) + return res + rv = _sqrt_mod_prime_power(a, p, 1) + if not rv: + return None + r = rv[0] + fr = r**2 - a + # hensel lifting with Newton iteration, see Ref.[3] chapter 9 + # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2 + n = 1 + px = p + while 1: + n1 = n + n1 *= 2 + if n1 > k: + break + n = n1 + px = px**2 + frinv = igcdex(2*r, px)[0] + r = (r - fr*frinv) % px + fr = r**2 - a + if n < k: + px = p**k + frinv = igcdex(2*r, px)[0] + r = (r - fr*frinv) % px + return [r, px - r] + + +def _sqrt_mod1(a, p, n): + """ + Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` + + see http://www.numbertheory.org/php/squareroot.html + """ + pn = p**n + a = a % pn + if a == 0: + # case gcd(a, p**k) = p**n + m = n // 2 + if n % 2 == 1: + pm1 = p**(m + 1) + def _iter0a(): + i = 0 + while i < pn: + yield i + i += pm1 + return _iter0a() + else: + pm = p**m + def _iter0b(): + i = 0 + while i < pn: + yield i + i += pm + return _iter0b() + + # case gcd(a, p**k) = p**r, r < n + f = factorint(a) + r = f[p] + if r % 2 == 1: + return None + m = r // 2 + a1 = a >> r + if p == 2: + if n - r == 1: + pnm1 = 1 << (n - m + 1) + pm1 = 1 << (m + 1) + def _iter1(): + k = 1 << (m + 2) + i = 1 << m + while i < pnm1: + j = i + while j < pn: + yield j + j += k + i += pm1 + return _iter1() + if n - r == 2: + res = _sqrt_mod_prime_power(a1, p, n - r) + if res is None: + return None + pnm = 1 << (n - m) + def _iter2(): + s = set() + for r in res: + i = 0 + while i < pn: + x = (r << m) + i + if x not in s: + s.add(x) + yield x + i += pnm + return _iter2() + if n - r > 2: + res = _sqrt_mod_prime_power(a1, p, n - r) + if res is None: + return None + pnm1 = 1 << (n - m - 1) + def _iter3(): + s = set() + for r in res: + i = 0 + while i < pn: + x = ((r << m) + i) % pn + if x not in s: + s.add(x) + yield x + i += pnm1 + return _iter3() + else: + m = r // 2 + a1 = a // p**r + res1 = _sqrt_mod_prime_power(a1, p, n - r) + if res1 is None: + return None + pm = p**m + pnr = p**(n-r) + pnm = p**(n-m) + + def _iter4(): + s = set() + pm = p**m + for rx in res1: + i = 0 + while i < pnm: + x = ((rx + i) % pn) + if x not in s: + s.add(x) + yield x*pm + i += pnr + return _iter4() + + +def is_quad_residue(a, p): + """ + Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, + i.e a % p in set([i**2 % p for i in range(p)]). + + Examples + ======== + + If ``p`` is an odd + prime, an iterative method is used to make the determination: + + >>> from sympy.ntheory import is_quad_residue + >>> sorted(set([i**2 % 7 for i in range(7)])) + [0, 1, 2, 4] + >>> [j for j in range(7) if is_quad_residue(j, 7)] + [0, 1, 2, 4] + + See Also + ======== + + legendre_symbol, jacobi_symbol + """ + a, p = as_int(a), as_int(p) + if p < 1: + raise ValueError('p must be > 0') + if a >= p or a < 0: + a = a % p + if a < 2 or p < 3: + return True + if not isprime(p): + if p % 2 and jacobi_symbol(a, p) == -1: + return False + r = sqrt_mod(a, p) + if r is None: + return False + else: + return True + + return pow(a, (p - 1) // 2, p) == 1 + + +def is_nthpow_residue(a, n, m): + """ + Returns True if ``x**n == a (mod m)`` has solutions. + + References + ========== + + .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 + + """ + a = a % m + a, n, m = as_int(a), as_int(n), as_int(m) + if m <= 0: + raise ValueError('m must be > 0') + if n < 0: + raise ValueError('n must be >= 0') + if n == 0: + if m == 1: + return False + return a == 1 + if a == 0: + return True + if n == 1: + return True + if n == 2: + return is_quad_residue(a, m) + return _is_nthpow_residue_bign(a, n, m) + + +def _is_nthpow_residue_bign(a, n, m): + r"""Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`.""" + # assert n > 2 + # assert a > 0 and m > 0 + if primitive_root(m) is None or igcd(a, m) != 1: + # assert m >= 8 + for prime, power in factorint(m).items(): + if not _is_nthpow_residue_bign_prime_power(a, n, prime, power): + return False + return True + f = totient(m) + k = int(f // igcd(f, n)) + return pow(a, k, int(m)) == 1 + + +def _is_nthpow_residue_bign_prime_power(a, n, p, k): + r"""Returns True/False if a solution for `x^n = a \pmod{p^k}` + does/does not exist.""" + # assert a > 0 + # assert n > 2 + # assert p is prime + # assert k > 0 + if a % p: + if p != 2: + return _is_nthpow_residue_bign(a, n, pow(p, k)) + if n & 1: + return True + c = trailing(n) + return a % pow(2, min(c + 2, k)) == 1 + else: + a %= pow(p, k) + if not a: + return True + mu = multiplicity(p, a) + if mu % n: + return False + pm = pow(p, mu) + return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu) + + +def _nthroot_mod2(s, q, p): + f = factorint(q) + v = [] + for b, e in f.items(): + v.extend([b]*e) + for qx in v: + s = _nthroot_mod1(s, qx, p, False) + return s + + +def _nthroot_mod1(s, q, p, all_roots): + """ + Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` + + References + ========== + + .. [1] A. M. Johnston "A Generalized qth Root Algorithm" + + """ + g = primitive_root(p) + if not isprime(q): + r = _nthroot_mod2(s, q, p) + else: + f = p - 1 + assert (p - 1) % q == 0 + # determine k + k = 0 + while f % q == 0: + k += 1 + f = f // q + # find z, x, r1 + f1 = igcdex(-f, q)[0] % q + z = f*f1 + x = (1 + z) // q + r1 = pow(s, x, p) + s1 = pow(s, f, p) + h = pow(g, f*q, p) + t = discrete_log(p, s1, h) + g2 = pow(g, z*t, p) + g3 = igcdex(g2, p)[0] + r = r1*g3 % p + #assert pow(r, q, p) == s + res = [r] + h = pow(g, (p - 1) // q, p) + #assert pow(h, q, p) == 1 + hx = r + for i in range(q - 1): + hx = (hx*h) % p + res.append(hx) + if all_roots: + res.sort() + return res + return min(res) + + + +def _help(m, prime_modulo_method, diff_method, expr_val): + """ + Helper function for _nthroot_mod_composite and polynomial_congruence. + + Parameters + ========== + + m : positive integer + prime_modulo_method : function to calculate the root of the congruence + equation for the prime divisors of m + diff_method : function to calculate derivative of expression at any + given point + expr_val : function to calculate value of the expression at any + given point + """ + from sympy.ntheory.modular import crt + f = factorint(m) + dd = {} + for p, e in f.items(): + tot_roots = set() + if e == 1: + tot_roots.update(prime_modulo_method(p)) + else: + for root in prime_modulo_method(p): + diff = diff_method(root, p) + if diff != 0: + ppow = p + m_inv = mod_inverse(diff, p) + for j in range(1, e): + ppow *= p + root = (root - expr_val(root, ppow) * m_inv) % ppow + tot_roots.add(root) + else: + new_base = p + roots_in_base = {root} + while new_base < pow(p, e): + new_base *= p + new_roots = set() + for k in roots_in_base: + if expr_val(k, new_base)!= 0: + continue + while k not in new_roots: + new_roots.add(k) + k = (k + (new_base // p)) % new_base + roots_in_base = new_roots + tot_roots = tot_roots | roots_in_base + if tot_roots == set(): + return [] + dd[pow(p, e)] = tot_roots + a = [] + m = [] + for x, y in dd.items(): + m.append(x) + a.append(list(y)) + return sorted({crt(m, list(i))[0] for i in product(*a)}) + + +def _nthroot_mod_composite(a, n, m): + """ + Find the solutions to ``x**n = a mod m`` when m is not prime. + """ + return _help(m, + lambda p: nthroot_mod(a, n, p, True), + lambda root, p: (pow(root, n - 1, p) * (n % p)) % p, + lambda root, p: (pow(root, n, p) - a) % p) + + +def nthroot_mod(a, n, p, all_roots=False): + """ + Find the solutions to ``x**n = a mod p``. + + Parameters + ========== + + a : integer + n : positive integer + p : positive integer + all_roots : if False returns the smallest root, else the list of roots + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import nthroot_mod + >>> nthroot_mod(11, 4, 19) + 8 + >>> nthroot_mod(11, 4, 19, True) + [8, 11] + >>> nthroot_mod(68, 3, 109) + 23 + """ + a = a % p + a, n, p = as_int(a), as_int(n), as_int(p) + + if n == 2: + return sqrt_mod(a, p, all_roots) + # see Hackman "Elementary Number Theory" (2009), page 76 + if not isprime(p): + return _nthroot_mod_composite(a, n, p) + if a % p == 0: + return [0] + if not is_nthpow_residue(a, n, p): + return [] if all_roots else None + if (p - 1) % n == 0: + return _nthroot_mod1(a, n, p, all_roots) + # The roots of ``x**n - a = 0 (mod p)`` are roots of + # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)`` + pa = n + pb = p - 1 + b = 1 + if pa < pb: + a, pa, b, pb = b, pb, a, pa + while pb: + # x**pa - a = 0; x**pb - b = 0 + # x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a = + # b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p + q, r = divmod(pa, pb) + c = pow(b, q, p) + c = igcdex(c, p)[0] + c = (c * a) % p + pa, pb = pb, r + a, b = b, c + if pa == 1: + if all_roots: + res = [a] + else: + res = a + elif pa == 2: + return sqrt_mod(a, p, all_roots) + else: + res = _nthroot_mod1(a, pa, p, all_roots) + return res + + +def quadratic_residues(p) -> list[int]: + """ + Returns the list of quadratic residues. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import quadratic_residues + >>> quadratic_residues(7) + [0, 1, 2, 4] + """ + p = as_int(p) + r = {pow(i, 2, p) for i in range(p // 2 + 1)} + return sorted(r) + + +def legendre_symbol(a, p): + r""" + Returns the Legendre symbol `(a / p)`. + + For an integer ``a`` and an odd prime ``p``, the Legendre symbol is + defined as + + .. math :: + \genfrac(){}{}{a}{p} = \begin{cases} + 0 & \text{if } p \text{ divides } a\\ + 1 & \text{if } a \text{ is a quadratic residue modulo } p\\ + -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p + \end{cases} + + Parameters + ========== + + a : integer + p : odd prime + + Examples + ======== + + >>> from sympy.ntheory import legendre_symbol + >>> [legendre_symbol(i, 7) for i in range(7)] + [0, 1, 1, -1, 1, -1, -1] + >>> sorted(set([i**2 % 7 for i in range(7)])) + [0, 1, 2, 4] + + See Also + ======== + + is_quad_residue, jacobi_symbol + + """ + a, p = as_int(a), as_int(p) + if not isprime(p) or p == 2: + raise ValueError("p should be an odd prime") + a = a % p + if not a: + return 0 + if pow(a, (p - 1) // 2, p) == 1: + return 1 + return -1 + + +def jacobi_symbol(m, n): + r""" + Returns the Jacobi symbol `(m / n)`. + + For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol + is defined as the product of the Legendre symbols corresponding to the + prime factors of ``n``: + + .. math :: + \genfrac(){}{}{m}{n} = + \genfrac(){}{}{m}{p^{1}}^{\alpha_1} + \genfrac(){}{}{m}{p^{2}}^{\alpha_2} + ... + \genfrac(){}{}{m}{p^{k}}^{\alpha_k} + \text{ where } n = + p_1^{\alpha_1} + p_2^{\alpha_2} + ... + p_k^{\alpha_k} + + Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1` + then ``m`` is a quadratic nonresidue modulo ``n``. + + But, unlike the Legendre symbol, if the Jacobi symbol + `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue + modulo ``n``. + + Parameters + ========== + + m : integer + n : odd positive integer + + Examples + ======== + + >>> from sympy.ntheory import jacobi_symbol, legendre_symbol + >>> from sympy import S + >>> jacobi_symbol(45, 77) + -1 + >>> jacobi_symbol(60, 121) + 1 + + The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can + be demonstrated as follows: + + >>> L = legendre_symbol + >>> S(45).factors() + {3: 2, 5: 1} + >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1 + True + + See Also + ======== + + is_quad_residue, legendre_symbol + """ + m, n = as_int(m), as_int(n) + if n < 0 or not n % 2: + raise ValueError("n should be an odd positive integer") + if m < 0 or m > n: + m %= n + if not m: + return int(n == 1) + if n == 1 or m == 1: + return 1 + if igcd(m, n) != 1: + return 0 + + j = 1 + while m != 0: + while m % 2 == 0 and m > 0: + m >>= 1 + if n % 8 in [3, 5]: + j = -j + m, n = n, m + if m % 4 == n % 4 == 3: + j = -j + m %= n + return j + + +class mobius(Function): + """ + Mobius function maps natural number to {-1, 0, 1} + + It is defined as follows: + 1) `1` if `n = 1`. + 2) `0` if `n` has a squared prime factor. + 3) `(-1)^k` if `n` is a square-free positive integer with `k` + number of prime factors. + + It is an important multiplicative function in number theory + and combinatorics. It has applications in mathematical series, + algebraic number theory and also physics (Fermion operator has very + concrete realization with Mobius Function model). + + Parameters + ========== + + n : positive integer + + Examples + ======== + + >>> from sympy.ntheory import mobius + >>> mobius(13*7) + 1 + >>> mobius(1) + 1 + >>> mobius(13*7*5) + -1 + >>> mobius(13**2) + 0 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function + .. [2] Thomas Koshy "Elementary Number Theory with Applications" + + """ + @classmethod + def eval(cls, n): + if n.is_integer: + if n.is_positive is not True: + raise ValueError("n should be a positive integer") + else: + raise TypeError("n should be an integer") + if n.is_prime: + return S.NegativeOne + elif n is S.One: + return S.One + elif n.is_Integer: + a = factorint(n) + if any(i > 1 for i in a.values()): + return S.Zero + return S.NegativeOne**len(a) + + +def _discrete_log_trial_mul(n, a, b, order=None): + """ + Trial multiplication algorithm for computing the discrete logarithm of + ``a`` to the base ``b`` modulo ``n``. + + The algorithm finds the discrete logarithm using exhaustive search. This + naive method is used as fallback algorithm of ``discrete_log`` when the + group order is very small. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul + >>> _discrete_log_trial_mul(41, 15, 7) + 3 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + if order is None: + order = n + x = 1 + for i in range(order): + if x == a: + return i + x = x * b % n + raise ValueError("Log does not exist") + + +def _discrete_log_shanks_steps(n, a, b, order=None): + """ + Baby-step giant-step algorithm for computing the discrete logarithm of + ``a`` to the base ``b`` modulo ``n``. + + The algorithm is a time-memory trade-off of the method of exhaustive + search. It uses `O(sqrt(m))` memory, where `m` is the group order. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps + >>> _discrete_log_shanks_steps(41, 15, 7) + 3 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + if order is None: + order = n_order(b, n) + m = isqrt(order) + 1 + T = {} + x = 1 + for i in range(m): + T[x] = i + x = x * b % n + z = mod_inverse(b, n) + z = pow(z, m, n) + x = a + for i in range(m): + if x in T: + return i * m + T[x] + x = x * z % n + raise ValueError("Log does not exist") + + +def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None): + """ + Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to + the base ``b`` modulo ``n``. + + It is a randomized algorithm with the same expected running time as + ``_discrete_log_shanks_steps``, but requires a negligible amount of memory. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho + >>> _discrete_log_pollard_rho(227, 3**7, 3) + 7 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + + if order is None: + order = n_order(b, n) + randint = _randint(rseed) + + for i in range(retries): + aa = randint(1, order - 1) + ba = randint(1, order - 1) + xa = pow(b, aa, n) * pow(a, ba, n) % n + + c = xa % 3 + if c == 0: + xb = a * xa % n + ab = aa + bb = (ba + 1) % order + elif c == 1: + xb = xa * xa % n + ab = (aa + aa) % order + bb = (ba + ba) % order + else: + xb = b * xa % n + ab = (aa + 1) % order + bb = ba + + for j in range(order): + c = xa % 3 + if c == 0: + xa = a * xa % n + ba = (ba + 1) % order + elif c == 1: + xa = xa * xa % n + aa = (aa + aa) % order + ba = (ba + ba) % order + else: + xa = b * xa % n + aa = (aa + 1) % order + + c = xb % 3 + if c == 0: + xb = a * xb % n + bb = (bb + 1) % order + elif c == 1: + xb = xb * xb % n + ab = (ab + ab) % order + bb = (bb + bb) % order + else: + xb = b * xb % n + ab = (ab + 1) % order + + c = xb % 3 + if c == 0: + xb = a * xb % n + bb = (bb + 1) % order + elif c == 1: + xb = xb * xb % n + ab = (ab + ab) % order + bb = (bb + bb) % order + else: + xb = b * xb % n + ab = (ab + 1) % order + + if xa == xb: + r = (ba - bb) % order + try: + e = mod_inverse(r, order) * (ab - aa) % order + if (pow(b, e, n) - a) % n == 0: + return e + except ValueError: + pass + break + raise ValueError("Pollard's Rho failed to find logarithm") + + +def _discrete_log_pohlig_hellman(n, a, b, order=None): + """ + Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to + the base ``b`` modulo ``n``. + + In order to compute the discrete logarithm, the algorithm takes advantage + of the factorization of the group order. It is more efficient when the + group order factors into many small primes. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman + >>> _discrete_log_pohlig_hellman(251, 210, 71) + 197 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + from .modular import crt + a %= n + b %= n + + if order is None: + order = n_order(b, n) + + f = factorint(order) + l = [0] * len(f) + + for i, (pi, ri) in enumerate(f.items()): + for j in range(ri): + gj = pow(b, l[i], n) + aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n) + bj = pow(b, order // pi, n) + cj = discrete_log(n, aj, bj, pi, True) + l[i] += cj * pi**j + + d, _ = crt([pi**ri for pi, ri in f.items()], l) + return d + + +def discrete_log(n, a, b, order=None, prime_order=None): + """ + Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. + + This is a recursive function to reduce the discrete logarithm problem in + cyclic groups of composite order to the problem in cyclic groups of prime + order. + + It employs different algorithms depending on the problem (subgroup order + size, prime order or not): + + * Trial multiplication + * Baby-step giant-step + * Pollard's Rho + * Pohlig-Hellman + + Examples + ======== + + >>> from sympy.ntheory import discrete_log + >>> discrete_log(41, 15, 7) + 3 + + References + ========== + + .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html + .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + + """ + n, a, b = as_int(n), as_int(a), as_int(b) + if order is None: + order = n_order(b, n) + + if prime_order is None: + prime_order = isprime(order) + + if order < 1000: + return _discrete_log_trial_mul(n, a, b, order) + elif prime_order: + if order < 1000000000000: + return _discrete_log_shanks_steps(n, a, b, order) + return _discrete_log_pollard_rho(n, a, b, order) + + return _discrete_log_pohlig_hellman(n, a, b, order) + + + +def quadratic_congruence(a, b, c, p): + """ + Find the solutions to ``a x**2 + b x + c = 0 mod p. + + Parameters + ========== + + a : int + b : int + c : int + p : int + A positive integer. + """ + a = as_int(a) + b = as_int(b) + c = as_int(c) + p = as_int(p) + a = a % p + b = b % p + c = c % p + + if a == 0: + return linear_congruence(b, -c, p) + if p == 2: + roots = [] + if c % 2 == 0: + roots.append(0) + if (a + b + c) % 2 == 0: + roots.append(1) + return roots + if isprime(p): + inv_a = mod_inverse(a, p) + b *= inv_a + c *= inv_a + if b % 2 == 1: + b = b + p + d = ((b * b) // 4 - c) % p + y = sqrt_mod(d, p, all_roots=True) + res = set() + for i in y: + res.add((i - b // 2) % p) + return sorted(res) + y = sqrt_mod(b * b - 4 * a * c, 4 * a * p, all_roots=True) + res = set() + for i in y: + root = linear_congruence(2 * a, i - b, 4 * a * p) + for j in root: + res.add(j % p) + return sorted(res) + + +def _polynomial_congruence_prime(coefficients, p): + """A helper function used by polynomial_congruence. + It returns the root of a polynomial modulo prime number + by naive search from [0, p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + """ + + roots = [] + rank = len(coefficients) + for i in range(0, p): + f_val = 0 + for coeff in range(0,rank - 1): + f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p + f_val = f_val + coefficients[-1] + if f_val % p == 0: + roots.append(i) + return roots + + +def _diff_poly(root, coefficients, p): + """A helper function used by polynomial_congruence. + It returns the derivative of the polynomial evaluated at the + root (mod p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + root : integer + """ + + diff = 0 + rank = len(coefficients) + for coeff in range(0, rank - 1): + if not coefficients[coeff]: + continue + diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)* + coefficients[coeff]) % p + return diff % p + + +def _val_poly(root, coefficients, p): + """A helper function used by polynomial_congruence. + It returns value of the polynomial at root (mod p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + root : integer + """ + rank = len(coefficients) + f_val = 0 + for coeff in range(0, rank - 1): + f_val = (f_val + pow(root, rank - coeff - 1, p)* + coefficients[coeff]) % p + f_val = f_val + coefficients[-1] + return f_val % p + + +def _valid_expr(expr): + """ + return coefficients of expr if it is a univariate polynomial + with integer coefficients else raise a ValueError. + """ + + if not expr.is_polynomial(): + raise ValueError("The expression should be a polynomial") + polynomial = Poly(expr) + if not polynomial.is_univariate: + raise ValueError("The expression should be univariate") + if not polynomial.domain == ZZ: + raise ValueError("The expression should should have integer coefficients") + return polynomial.all_coeffs() + + +def polynomial_congruence(expr, m): + """ + Find the solutions to a polynomial congruence equation modulo m. + + Parameters + ========== + + coefficients : Coefficients of the Polynomial + m : positive integer + + Examples + ======== + + >>> from sympy.ntheory import polynomial_congruence + >>> from sympy.abc import x + >>> expr = x**6 - 2*x**5 -35 + >>> polynomial_congruence(expr, 6125) + [3257] + """ + coefficients = _valid_expr(expr) + coefficients = [num % m for num in coefficients] + rank = len(coefficients) + if rank == 3: + return quadratic_congruence(*coefficients, m) + if rank == 2: + return quadratic_congruence(0, *coefficients, m) + if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients): + return nthroot_mod(-coefficients[-1], rank - 1, m, True) + if isprime(m): + return _polynomial_congruence_prime(coefficients, m) + return _help(m, + lambda p: _polynomial_congruence_prime(coefficients, p), + lambda root, p: _diff_poly(root, coefficients, p), + lambda root, p: _val_poly(root, coefficients, p)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87e47b655edb7f48f2d9f20f799e86ca6d5254e9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5f63a680be696e16095f7dacb90f816853f8bd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e1b5c5f1d574f7c0b229ff882983c78d0306c5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ca9f44663d8213d250641a89d7e9cda6cf04278 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b32ce4e01ab3fed3a70fcbb39f5e3d8c631c5e6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3793eea8839c4f3faf67a47806f1e6a1b052215f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51d06928268398963cabcf18c057e2266cc5939a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5c0f7a10a1c01d45d860664d097c8ff1133914c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3923187b34cde8126aedc39d55cc3ea30d3ac5fe Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0b1b2e764917685cd7fb46f6d569a687d91f3da Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0405f9bf6dc4bc08fb8068eb1ce77e66ee8a873 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py new file mode 100644 index 0000000000000000000000000000000000000000..c18188e3c8a308c102e97434078915317763b33c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py @@ -0,0 +1,133 @@ +from sympy.core.random import randint + +from sympy.ntheory.bbp_pi import pi_hex_digits +from sympy.testing.pytest import raises + + +# http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html +# There are actually 8336 listed there; with the prepended 3 there are 8337 +# below +dig=''.join(''' +3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013 +77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5 +ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc +16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59 +b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a +3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10 +b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793 +1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9 +91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442 +392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f +68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e +888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77 +061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de +f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53 +b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b +b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3 +cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df +829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58 +c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97 +90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091 +98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0 +1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74 +e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14 +77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3 +5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9 +c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6 +e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556 +6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df +7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a +3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb +266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007 +373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574 +b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd +a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9 +086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f +2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d +fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4 +dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb +fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d +0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b +3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff +28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761 +70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade +14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4 +b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812 +810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30 +548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13 +e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d +c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2 +85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e +41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997 +35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588 +cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad +f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4 +6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f +45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429 +f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6 +b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18 +5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895 +2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125 +f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86 +dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c +60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9 +2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48 +fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b +0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d +9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31 +2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed +fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3 +fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab +71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd +c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457 +708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246 +33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906 +fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806 +b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6 +deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8 +fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e +c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d +1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190 +45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d +c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e +f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562 +e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7 +972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5 +4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560 +55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07 +2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9 +f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe +32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0 +dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd +d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13 +57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0 +486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79 +4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada +380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc +2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4 +42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334 +8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e +6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb +b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b +9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3 +d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa +7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2 +5b578fdfe33ac372e6'''.split()) + + +def test_hex_pi_nth_digits(): + assert pi_hex_digits(0) == '3243f6a8885a30' + assert pi_hex_digits(1) == '243f6a8885a308' + assert pi_hex_digits(10000) == '68ac8fcfb8016c' + assert pi_hex_digits(13) == '08d313198a2e03' + assert pi_hex_digits(0, 3) == '324' + assert pi_hex_digits(0, 0) == '' + raises(ValueError, lambda: pi_hex_digits(-1)) + raises(ValueError, lambda: pi_hex_digits(3.14)) + + # this will pick a random segment to compute every time + # it is run. If it ever fails, there is an error in the + # computation. + n = randint(0, len(dig)) + prec = randint(0, len(dig) - n) + assert pi_hex_digits(n, prec) == dig[n: n + prec] diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..babab948f121ea343b96a61f78386210bcac6b16 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py @@ -0,0 +1,73 @@ +from sympy.core import GoldenRatio as phi +from sympy.core.numbers import (Rational, pi) +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.ntheory.continued_fraction import \ + (continued_fraction_periodic as cf_p, + continued_fraction_iterator as cf_i, + continued_fraction_convergents as cf_c, + continued_fraction_reduce as cf_r, + continued_fraction as cf) +from sympy.testing.pytest import raises + + +def test_continued_fraction(): + assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1) + assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1) + t = sqrt(2) + assert cf((1 + t)*(1 - t)) == cf(-1) + for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5, + (2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]: + assert (cf_r(cf(n)) - n).expand() == 0 + assert (cf_r(cf(-n)) + n).expand() == 0 + raises(ValueError, lambda: cf(sqrt(2 + sqrt(3)))) + raises(ValueError, lambda: cf(sqrt(2) + sqrt(3))) + raises(ValueError, lambda: cf(pi)) + raises(ValueError, lambda: cf(.1)) + + raises(ValueError, lambda: cf_p(1, 0, 0)) + raises(ValueError, lambda: cf_p(1, 1, -1)) + assert cf_p(4, 3, 0) == [1, 3] + assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]] + assert cf_p(1, 1, 0) == [1] + assert cf_p(3, 4, 0) == [0, 1, 3] + assert cf_p(4, 5, 0) == [0, 1, 4] + assert cf_p(5, 6, 0) == [0, 1, 5] + assert cf_p(11, 13, 0) == [0, 1, 5, 2] + assert cf_p(16, 19, 0) == [0, 1, 5, 3] + assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2] + assert cf_p(1, 2, 5) == [[1]] + assert cf_p(0, 1, 2) == [1, [2]] + assert cf_p(6, 7, 49) == [1, 1, 6] + assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4] + assert cf_p(3245, 10000) == [0, 3, 12, 4, 13] + assert cf_p(1932, 2568) == [0, 1, 3, 26, 2] + assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23] + + def take(iterator, n=7): + res = [] + for i, t in enumerate(cf_i(iterator)): + if i >= n: + break + res.append(t) + return res + + assert take(phi) == [1, 1, 1, 1, 1, 1, 1] + assert take(pi) == [3, 7, 15, 1, 292, 1, 1] + + assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2] + assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2] + + assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)] + assert list(cf_c([2])) == [S(2)] + assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), + Rational(8, 5), Rational(13, 8), Rational(21, 13)] + assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)] + + assert cf_r([1, 6, 1, 8]) == Rational(71, 62) + assert cf_r([3]) == S(3) + assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29) + assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0 + assert cf_r([1, 5, 9]) == Rational(55, 46) + assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0 + assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py new file mode 100644 index 0000000000000000000000000000000000000000..6e58ff31aec7609407a8d90afd0bbdacebb66935 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py @@ -0,0 +1,34 @@ +from sympy.ntheory import count_digits, digits, is_palindromic + +from sympy.testing.pytest import raises + + +def test_digits(): + assert all([digits(n, 2)[1:] == [int(d) for d in format(n, 'b')] + for n in range(20)]) + assert all([digits(n, 8)[1:] == [int(d) for d in format(n, 'o')] + for n in range(20)]) + assert all([digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')] + for n in range(20)]) + assert digits(2345, 34) == [34, 2, 0, 33] + assert digits(384753, 71) == [71, 1, 5, 23, 4] + assert digits(93409, 10) == [10, 9, 3, 4, 0, 9] + assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9] + assert digits(35, 10) == [10, 3, 5] + assert digits(35, 10, 3) == [10, 0, 3, 5] + assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5] + raises(ValueError, lambda: digits(2, 2, 1)) + + +def test_count_digits(): + assert count_digits(55, 2) == {1: 5, 0: 1} + assert count_digits(55, 10) == {5: 2} + n = count_digits(123) + assert n[4] == 0 and type(n[4]) is int + + +def test_is_palindromic(): + assert is_palindromic(-11) + assert is_palindromic(11) + assert is_palindromic(0o121, 8) + assert not is_palindromic(123) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dbffee209539d9f81981f89c77337b583fa42b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py @@ -0,0 +1,63 @@ +from sympy.ntheory.ecm import ecm, Point +from sympy.testing.pytest import slow + +@slow +def test_ecm(): + assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297} + assert ecm(46167045131415113) == {43, 2634823, 407485517} + assert ecm(631211032315670776841) == {9312934919, 67777885039} + assert ecm(398883434337287) == {99476569, 4009823} + assert ecm(64211816600515193) == {281719, 359641, 633767} + assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123} + assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571} + assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803} + assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721} + #This takes ~10secs while factorint is not able to factorize this even in ~10mins + assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809} + + +def test_Point(): + from sympy.core.numbers import mod_inverse + #The curve is of the form y**2 = x**3 + a*x**2 + x + mod = 101 + a = 10 + a_24 = (a + 2)*mod_inverse(4, mod) + p1 = Point(10, 17, a_24, mod) + p2 = p1.double() + assert p2 == Point(68, 56, a_24, mod) + p4 = p2.double() + assert p4 == Point(22, 64, a_24, mod) + p8 = p4.double() + assert p8 == Point(71, 95, a_24, mod) + p16 = p8.double() + assert p16 == Point(5, 16, a_24, mod) + p32 = p16.double() + assert p32 == Point(33, 96, a_24, mod) + + # p3 = p2 + p1 + p3 = p2.add(p1, p1) + assert p3 == Point(1, 61, a_24, mod) + # p5 = p3 + p2 or p4 + p1 + p5 = p3.add(p2, p1) + assert p5 == Point(49, 90, a_24, mod) + assert p5 == p4.add(p1, p3) + # p6 = 2*p3 + p6 = p3.double() + assert p6 == Point(87, 43, a_24, mod) + assert p6 == p4.add(p2, p2) + # p7 = p5 + p2 + p7 = p5.add(p2, p3) + assert p7 == Point(69, 23, a_24, mod) + assert p7 == p4.add(p3, p1) + assert p7 == p6.add(p1, p5) + # p9 = p5 + p4 + p9 = p5.add(p4, p1) + assert p9 == Point(56, 99, a_24, mod) + assert p9 == p6.add(p3, p3) + assert p9 == p7.add(p2, p5) + assert p9 == p8.add(p1, p7) + + assert p5 == p1.mont_ladder(5) + assert p9 == p1.mont_ladder(9) + assert p16 == p1.mont_ladder(16) + assert p9 == p3.mont_ladder(3) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a9fac578d93a88a648bdcf8dc34550cf4a7573 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py @@ -0,0 +1,49 @@ +from sympy.core.numbers import Rational +from sympy.ntheory.egyptian_fraction import egyptian_fraction +from sympy.core.add import Add +from sympy.testing.pytest import raises +from sympy.core.random import random_complex_number + + +def test_egyptian_fraction(): + def test_equality(r, alg="Greedy"): + return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)]) + + r = random_complex_number(a=0, c=1, b=0, d=0, rational=True) + assert test_equality(r) + + assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345] + assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26] + assert egyptian_fraction(Rational(23, 101), "Greedy") == \ + [5, 37, 1438, 2985448, 40108045937720] + assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \ + [2, 6, 12, 35, 276, 2415] + assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \ + [6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807, + 1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443, + 3267056, 3581556, 10192056, 10650056950806] + assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30] + assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737] + raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9))) + assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7, + 14, 574, 2788, 6460, + 11590, 33062, 113820] + assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 27, 744, 893588, + 1251493536607, + 20361068938197002344405230] + + +def test_input(): + r = (2,3), Rational(2, 3), (Rational(2), Rational(3)) + for m in ["Greedy", "Graham Jewett", "Takenouchi", "Golomb"]: + for i in r: + d = egyptian_fraction(i, m) + assert all(i.is_Integer for i in d) + if m == "Graham Jewett": + assert d == [3, 4, 12] + else: + assert d == [2, 6] + # check prefix + d = egyptian_fraction(Rational(5, 3)) + assert d == [1, 2, 6] and all(i.is_Integer for i in d) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..7d49d8eac72cc622fb92dfca8c54e5cc6c8dfb8f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py @@ -0,0 +1,20 @@ +from sympy.ntheory.elliptic_curve import EllipticCurve + + +def test_elliptic_curve(): + # Point addition and multiplication + e3 = EllipticCurve(-1, 9) + p = e3(0, 3) + q = e3(-1, 3) + r = p + q + assert r.x == 1 and r.y == -3 + r = 2*p + q + assert r.x == 35 and r.y == 207 + r = -p + q + assert r.x == 37 and r.y == 225 + # Verify result in http://www.lmfdb.org/EllipticCurve/Q + # Discriminant + assert EllipticCurve(-1, 9).discriminant == -34928 + assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088 + # Torsion points + assert len(EllipticCurve(0, 1).torsion_points()) == 6 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py new file mode 100644 index 0000000000000000000000000000000000000000..626dde0dec87d45d83a635eda3af441e3a635e66 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py @@ -0,0 +1,685 @@ +from sympy.concrete.summations import summation +from sympy.core.containers import Dict +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.combinatorial.factorials import factorial as fac +from sympy.core.evalf import bitcount +from sympy.core.numbers import Integer, Rational + +from sympy.ntheory import (totient, + factorint, primefactors, divisors, nextprime, + primerange, pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial, + trailing, divisor_count, primorial, pollard_pm1, divisor_sigma, + factorrat, reduced_totient) +from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors, + antidivisors, antidivisor_count, core, udivisors, udivisor_sigma, + udivisor_count, proper_divisor_count, primenu, primeomega, small_trailing, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, dra, drm) + +from sympy.testing.pytest import raises, slow + +from sympy.utilities.iterables import capture + + +def fac_multiplicity(n, p): + """Return the power of the prime number p in the + factorization of n!""" + if p > n: + return 0 + if p > n//2: + return 1 + q, m = n, 0 + while q >= p: + q //= p + m += q + return m + + +def multiproduct(seq=(), start=1): + """ + Return the product of a sequence of factors with multiplicities, + times the value of the parameter ``start``. The input may be a + sequence of (factor, exponent) pairs or a dict of such pairs. + + >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 + 279936 + + """ + if not seq: + return start + if isinstance(seq, dict): + seq = iter(seq.items()) + units = start + multi = [] + for base, exp in seq: + if not exp: + continue + elif exp == 1: + units *= base + else: + if exp % 2: + units *= base + multi.append((base, exp//2)) + return units * multiproduct(multi)**2 + + +def test_trailing_bitcount(): + assert trailing(0) == 0 + assert trailing(1) == 0 + assert trailing(-1) == 0 + assert trailing(2) == 1 + assert trailing(7) == 0 + assert trailing(-7) == 0 + for i in range(100): + assert trailing(1 << i) == i + assert trailing((1 << i) * 31337) == i + assert trailing(1 << 1000001) == 1000001 + assert trailing((1 << 273956)*7**37) == 273956 + # issue 12709 + big = small_trailing[-1]*2 + assert trailing(-big) == trailing(big) + assert bitcount(-big) == bitcount(big) + + +def test_multiplicity(): + for b in range(2, 20): + for i in range(100): + assert multiplicity(b, b**i) == i + assert multiplicity(b, (b**i) * 23) == i + assert multiplicity(b, (b**i) * 1000249) == i + # Should be fast + assert multiplicity(10, 10**10023) == 10023 + # Should exit quickly + assert multiplicity(10**10, 10**10) == 1 + # Should raise errors for bad input + raises(ValueError, lambda: multiplicity(1, 1)) + raises(ValueError, lambda: multiplicity(1, 2)) + raises(ValueError, lambda: multiplicity(1.3, 2)) + raises(ValueError, lambda: multiplicity(2, 0)) + raises(ValueError, lambda: multiplicity(1.3, 0)) + + # handles Rationals + assert multiplicity(10, Rational(30, 7)) == 1 + assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1 + assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2 + assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1 + assert multiplicity(3, Rational(1, 9)) == -2 + + +def test_multiplicity_in_factorial(): + n = fac(1000) + for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96): + assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000) + + +def test_perfect_power(): + raises(ValueError, lambda: perfect_power(0.1)) + assert perfect_power(0) is False + assert perfect_power(1) is False + assert perfect_power(2) is False + assert perfect_power(3) is False + assert perfect_power(4) == (2, 2) + assert perfect_power(14) is False + assert perfect_power(25) == (5, 2) + assert perfect_power(22) is False + assert perfect_power(22, [2]) is False + assert perfect_power(137**(3*5*13)) == (137, 3*5*13) + assert perfect_power(137**(3*5*13) + 1) is False + assert perfect_power(137**(3*5*13) - 1) is False + assert perfect_power(103005006004**7) == (103005006004, 7) + assert perfect_power(103005006004**7 + 1) is False + assert perfect_power(103005006004**7 - 1) is False + assert perfect_power(103005006004**12) == (103005006004, 12) + assert perfect_power(103005006004**12 + 1) is False + assert perfect_power(103005006004**12 - 1) is False + assert perfect_power(2**10007) == (2, 10007) + assert perfect_power(2**10007 + 1) is False + assert perfect_power(2**10007 - 1) is False + assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60) + assert perfect_power((9**99 + 1)**60 + 1) is False + assert perfect_power((9**99 + 1)**60 - 1) is False + assert perfect_power((10**40000)**2, big=False) == (10**40000, 2) + assert perfect_power(10**100000) == (10, 100000) + assert perfect_power(10**100001) == (10, 100001) + assert perfect_power(13**4, [3, 5]) is False + assert perfect_power(3**4, [3, 10], factor=0) is False + assert perfect_power(3**3*5**3) == (15, 3) + assert perfect_power(2**3*5**5) is False + assert perfect_power(2*13**4) is False + assert perfect_power(2**5*3**3) is False + t = 2**24 + for d in divisors(24): + m = perfect_power(t*3**d) + assert m and m[1] == d or d == 1 + m = perfect_power(t*3**d, big=False) + assert m and m[1] == 2 or d == 1 or d == 3, (d, m) + + # negatives and non-integer rationals + assert perfect_power(-4) is False + assert perfect_power(-8) == (-2, 3) + assert perfect_power(Rational(1, 2)**3) == (S.Half, 3) + assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3) + + +@slow +def test_factorint(): + assert primefactors(123456) == [2, 3, 643] + assert factorint(0) == {0: 1} + assert factorint(1) == {} + assert factorint(-1) == {-1: 1} + assert factorint(-2) == {-1: 1, 2: 1} + assert factorint(-16) == {-1: 1, 2: 4} + assert factorint(2) == {2: 1} + assert factorint(126) == {2: 1, 3: 2, 7: 1} + assert factorint(123456) == {2: 6, 3: 1, 643: 1} + assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1} + assert factorint(64015937) == {7993: 1, 8009: 1} + assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1} + #issue 19683 + assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1} + #issue 17676 + assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1} + assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1} + assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1} + + assert factorint(0, multiple=True) == [0] + assert factorint(1, multiple=True) == [] + assert factorint(-1, multiple=True) == [-1] + assert factorint(-2, multiple=True) == [-1, 2] + assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2] + assert factorint(2, multiple=True) == [2] + assert factorint(24, multiple=True) == [2, 2, 2, 3] + assert factorint(126, multiple=True) == [2, 3, 3, 7] + assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643] + assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337] + assert factorint(64015937, multiple=True) == [7993, 8009] + assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721] + + assert factorint(fac(1, evaluate=False)) == {} + assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1} + assert factorint(fac(15, evaluate=False)) == \ + {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1} + assert factorint(fac(20, evaluate=False)) == \ + {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1} + assert factorint(fac(23, evaluate=False)) == \ + {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1} + + assert multiproduct(factorint(fac(200))) == fac(200) + assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200) + for b, e in factorint(fac(150)).items(): + assert e == fac_multiplicity(150, b) + for b, e in factorint(fac(150, evaluate=False)).items(): + assert e == fac_multiplicity(150, b) + assert factorint(103005006059**7) == {103005006059: 7} + assert factorint(31337**191) == {31337: 191} + assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \ + {2: 1000, 3: 500, 257: 127, 383: 60} + assert len(factorint(fac(10000))) == 1229 + assert len(factorint(fac(10000, evaluate=False))) == 1229 + assert factorint(12932983746293756928584532764589230) == \ + {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1} + assert factorint(727719592270351) == {727719592270351: 1} + assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1) + for n in range(60000): + assert multiproduct(factorint(n)) == n + assert pollard_rho(2**64 + 1, seed=1) == 274177 + assert pollard_rho(19, seed=1) is None + assert factorint(3, limit=2) == {3: 1} + assert factorint(12345) == {3: 1, 5: 1, 823: 1} + assert factorint( + 12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit + assert factorint(1, limit=1) == {} + assert factorint(0, 3) == {0: 1} + assert factorint(12, limit=1) == {12: 1} + assert factorint(30, limit=2) == {2: 1, 15: 1} + assert factorint(16, limit=2) == {2: 4} + assert factorint(124, limit=3) == {2: 2, 31: 1} + assert factorint(4*31**2, limit=3) == {2: 2, 31: 2} + p1 = nextprime(2**32) + p2 = nextprime(2**16) + p3 = nextprime(p2) + assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1} + assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1} + assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1} + assert factorint(primorial(17) + 1, use_pm1=0) == \ + {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1} + # when prime b is closer than approx sqrt(8*p) to prime p then they are + # "close" and have a trivial factorization + a = nextprime(2**2**8) # 78 digits + b = nextprime(a + 2**2**4) + assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1)) + + raises(ValueError, lambda: pollard_rho(4)) + raises(ValueError, lambda: pollard_pm1(3)) + raises(ValueError, lambda: pollard_pm1(10, B=2)) + # verbose coverage + n = nextprime(2**16)*nextprime(2**17)*nextprime(1901) + assert 'with primes' in capture(lambda: factorint(n, verbose=1)) + capture(lambda: factorint(nextprime(2**16)*1012, verbose=1)) + + n = nextprime(2**17) + capture(lambda: factorint(n**3, verbose=1)) # perfect power termination + capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg + + # exceed 1st + n = nextprime(2**17) + n *= nextprime(n) + assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1)) + n *= nextprime(n) + assert len(factorint(n)) == 3 + assert len(factorint(n, limit=p1)) == 3 + n *= nextprime(2*n) + # exceed 2nd + assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1)) + assert capture( + lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2 + # non-prime pm1 result + n = nextprime(8069) + n *= nextprime(2*n)*nextprime(2*n, 2) + capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result + # factor fermat composite + p1 = nextprime(2**17) + p2 = nextprime(2*p1) + assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6} + # Test for non integer input + raises(ValueError, lambda: factorint(4.5)) + # test dict/Dict input + sans = '2**10*3**3' + n = {4: 2, 12: 3} + assert str(factorint(n)) == sans + assert str(factorint(Dict(n))) == sans + + +def test_divisors_and_divisor_count(): + assert divisors(-1) == [1] + assert divisors(0) == [] + assert divisors(1) == [1] + assert divisors(2) == [1, 2] + assert divisors(3) == [1, 3] + assert divisors(17) == [1, 17] + assert divisors(10) == [1, 2, 5, 10] + assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100] + assert divisors(101) == [1, 101] + + assert divisor_count(0) == 0 + assert divisor_count(-1) == 1 + assert divisor_count(1) == 1 + assert divisor_count(6) == 4 + assert divisor_count(12) == 6 + + assert divisor_count(180, 3) == divisor_count(180//3) + assert divisor_count(2*3*5, 7) == 0 + + +def test_proper_divisors_and_proper_divisor_count(): + assert proper_divisors(-1) == [] + assert proper_divisors(0) == [] + assert proper_divisors(1) == [] + assert proper_divisors(2) == [1] + assert proper_divisors(3) == [1] + assert proper_divisors(17) == [1] + assert proper_divisors(10) == [1, 2, 5] + assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50] + assert proper_divisors(1000000007) == [1] + + assert proper_divisor_count(0) == 0 + assert proper_divisor_count(-1) == 0 + assert proper_divisor_count(1) == 0 + assert proper_divisor_count(36) == 8 + assert proper_divisor_count(2*3*5) == 7 + + +def test_udivisors_and_udivisor_count(): + assert udivisors(-1) == [1] + assert udivisors(0) == [] + assert udivisors(1) == [1] + assert udivisors(2) == [1, 2] + assert udivisors(3) == [1, 3] + assert udivisors(17) == [1, 17] + assert udivisors(10) == [1, 2, 5, 10] + assert udivisors(100) == [1, 4, 25, 100] + assert udivisors(101) == [1, 101] + assert udivisors(1000) == [1, 8, 125, 1000] + + assert udivisor_count(0) == 0 + assert udivisor_count(-1) == 1 + assert udivisor_count(1) == 1 + assert udivisor_count(6) == 4 + assert udivisor_count(12) == 4 + + assert udivisor_count(180) == 8 + assert udivisor_count(2*3*5*7) == 16 + + +def test_issue_6981(): + S = set(divisors(4)).union(set(divisors(Integer(2)))) + assert S == {1,2,4} + + +def test_totient(): + assert [totient(k) for k in range(1, 12)] == \ + [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10] + assert totient(5005) == 2880 + assert totient(5006) == 2502 + assert totient(5009) == 5008 + assert totient(2**100) == 2**99 + + raises(ValueError, lambda: totient(30.1)) + raises(ValueError, lambda: totient(20.001)) + + m = Symbol("m", integer=True) + assert totient(m) + assert totient(m).subs(m, 3**10) == 3**10 - 3**9 + assert summation(totient(m), (m, 1, 11)) == 42 + + n = Symbol("n", integer=True, positive=True) + assert totient(n).is_integer + + x=Symbol("x", integer=False) + raises(ValueError, lambda: totient(x)) + + y=Symbol("y", positive=False) + raises(ValueError, lambda: totient(y)) + + z=Symbol("z", positive=True, integer=True) + raises(ValueError, lambda: totient(2**(-z))) + + +def test_reduced_totient(): + assert [reduced_totient(k) for k in range(1, 16)] == \ + [1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4] + assert reduced_totient(5005) == 60 + assert reduced_totient(5006) == 2502 + assert reduced_totient(5009) == 5008 + assert reduced_totient(2**100) == 2**98 + + m = Symbol("m", integer=True) + assert reduced_totient(m) + assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9 + assert summation(reduced_totient(m), (m, 1, 16)) == 68 + + n = Symbol("n", integer=True, positive=True) + assert reduced_totient(n).is_integer + + +def test_divisor_sigma(): + assert [divisor_sigma(k) for k in range(1, 12)] == \ + [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12] + assert [divisor_sigma(k, 2) for k in range(1, 12)] == \ + [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122] + assert divisor_sigma(23450) == 50592 + assert divisor_sigma(23450, 0) == 24 + assert divisor_sigma(23450, 1) == 50592 + assert divisor_sigma(23450, 2) == 730747500 + assert divisor_sigma(23450, 3) == 14666785333344 + + a = Symbol("a", prime=True) + b = Symbol("b", prime=True) + j = Symbol("j", integer=True, positive=True) + k = Symbol("k", integer=True, positive=True) + assert divisor_sigma(a**j*b**k) == (a**(j + 1) - 1)*(b**(k + 1) - 1)/((a - 1)*(b - 1)) + assert divisor_sigma(a**j*b**k, 2) == (a**(2*j + 2) - 1)*(b**(2*k + 2) - 1)/((a**2 - 1)*(b**2 - 1)) + assert divisor_sigma(a**j*b**k, 0) == (j + 1)*(k + 1) + + m = Symbol("m", integer=True) + k = Symbol("k", integer=True) + assert divisor_sigma(m) + assert divisor_sigma(m, k) + assert divisor_sigma(m).subs(m, 3**10) == 88573 + assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597 + assert summation(divisor_sigma(m), (m, 1, 11)) == 99 + + +def test_udivisor_sigma(): + assert [udivisor_sigma(k) for k in range(1, 12)] == \ + [1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12] + assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \ + [1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332] + assert udivisor_sigma(23450) == 42432 + assert udivisor_sigma(23450, 0) == 16 + assert udivisor_sigma(23450, 1) == 42432 + assert udivisor_sigma(23450, 2) == 702685000 + assert udivisor_sigma(23450, 4) == 321426961814978248 + + m = Symbol("m", integer=True) + k = Symbol("k", integer=True) + assert udivisor_sigma(m) + assert udivisor_sigma(m, k) + assert udivisor_sigma(m).subs(m, 4**9) == 262145 + assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737 + assert summation(udivisor_sigma(m), (m, 2, 15)) == 169 + + +def test_issue_4356(): + assert factorint(1030903) == {53: 2, 367: 1} + + +def test_divisors(): + assert divisors(28) == [1, 2, 4, 7, 14, 28] + assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105] + assert divisors(0) == [] + + +def test_divisor_count(): + assert divisor_count(0) == 0 + assert divisor_count(6) == 4 + + +def test_proper_divisors(): + assert proper_divisors(-1) == [] + assert proper_divisors(28) == [1, 2, 4, 7, 14] + assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35] + + +def test_proper_divisor_count(): + assert proper_divisor_count(6) == 3 + assert proper_divisor_count(108) == 11 + + +def test_antidivisors(): + assert antidivisors(-1) == [] + assert antidivisors(-3) == [2] + assert antidivisors(14) == [3, 4, 9] + assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158] + assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230] + assert antidivisors(393216) == [262144] + assert sorted(x for x in antidivisors(3*5*7, 1)) == \ + [2, 6, 10, 11, 14, 19, 30, 42, 70] + assert antidivisors(1) == [] + + +def test_antidivisor_count(): + assert antidivisor_count(0) == 0 + assert antidivisor_count(-1) == 0 + assert antidivisor_count(-4) == 1 + assert antidivisor_count(20) == 3 + assert antidivisor_count(25) == 5 + assert antidivisor_count(38) == 7 + assert antidivisor_count(180) == 6 + assert antidivisor_count(2*3*5) == 3 + + +def test_smoothness_and_smoothness_p(): + assert smoothness(1) == (1, 1) + assert smoothness(2**4*3**2) == (3, 16) + + assert smoothness_p(10431, m=1) == \ + (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) + assert smoothness_p(10431) == \ + (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) + assert smoothness_p(10431, power=1) == \ + (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) + assert smoothness_p(21477639576571, visual=1) == \ + 'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \ + 'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931' + + +def test_visual_factorint(): + assert factorint(1, visual=1) == 1 + forty2 = factorint(42, visual=True) + assert type(forty2) == Mul + assert str(forty2) == '2**1*3**1*7**1' + assert factorint(1, visual=True) is S.One + no = {"evaluate": False} + assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no), + Pow(3, 2, **no), + Pow(7, 2, **no), **no) + assert -1 in factorint(-42, visual=True).args + + +def test_factorrat(): + assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1' + assert str(factorrat(Rational(1, 1), visual=True)) == '1' + assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)' + assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)' + assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)' + + assert factorrat(S(12)/1, multiple=True) == [2, 2, 3] + assert factorrat(Rational(1, 1), multiple=True) == [] + assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5] + assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5] + assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3] + assert factorrat(S(-25)/14/9, multiple=True) == \ + [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5] + + +def test_visual_io(): + sm = smoothness_p + fi = factorint + # with smoothness_p + n = 124 + d = fi(n) + m = fi(d, visual=True) + t = sm(n) + s = sm(t) + for th in [d, s, t, n, m]: + assert sm(th, visual=True) == s + assert sm(th, visual=1) == s + for th in [d, s, t, n, m]: + assert sm(th, visual=False) == t + assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t] + assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t] + + # with factorint + for th in [d, m, n]: + assert fi(th, visual=True) == m + assert fi(th, visual=1) == m + for th in [d, m, n]: + assert fi(th, visual=False) == d + assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d] + assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d] + + # test reevaluation + no = {"evaluate": False} + assert sm({4: 2}, visual=False) == sm(16) + assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), + visual=False) == sm(2**10) + + assert fi({4: 2}, visual=False) == fi(16) + assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), + visual=False) == fi(2**10) + + +def test_core(): + assert core(35**13, 10) == 42875 + assert core(210**2) == 1 + assert core(7776, 3) == 36 + assert core(10**27, 22) == 10**5 + assert core(537824) == 14 + assert core(1, 6) == 1 + + +def test_primenu(): + assert primenu(2) == 1 + assert primenu(2 * 3) == 2 + assert primenu(2 * 3 * 5) == 3 + assert primenu(3 * 25) == primenu(3) + primenu(25) + assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1] + assert primenu(fac(50)) == 15 + assert primenu(2 ** 9941 - 1) == 1 + n = Symbol('n', integer=True) + assert primenu(n) + assert primenu(n).subs(n, 2 ** 31 - 1) == 1 + assert summation(primenu(n), (n, 2, 30)) == 43 + + +def test_primeomega(): + assert primeomega(2) == 1 + assert primeomega(2 * 2) == 2 + assert primeomega(2 * 2 * 3) == 3 + assert primeomega(3 * 25) == primeomega(3) + primeomega(25) + assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1] + assert primeomega(fac(50)) == 108 + assert primeomega(2 ** 9941 - 1) == 1 + n = Symbol('n', integer=True) + assert primeomega(n) + assert primeomega(n).subs(n, 2 ** 31 - 1) == 1 + assert summation(primeomega(n), (n, 2, 30)) == 59 + + +def test_mersenne_prime_exponent(): + assert mersenne_prime_exponent(1) == 2 + assert mersenne_prime_exponent(4) == 7 + assert mersenne_prime_exponent(10) == 89 + assert mersenne_prime_exponent(25) == 21701 + raises(ValueError, lambda: mersenne_prime_exponent(52)) + raises(ValueError, lambda: mersenne_prime_exponent(0)) + + +def test_is_perfect(): + assert is_perfect(6) is True + assert is_perfect(15) is False + assert is_perfect(28) is True + assert is_perfect(400) is False + assert is_perfect(496) is True + assert is_perfect(8128) is True + assert is_perfect(10000) is False + + +def test_is_mersenne_prime(): + assert is_mersenne_prime(10) is False + assert is_mersenne_prime(127) is True + assert is_mersenne_prime(511) is False + assert is_mersenne_prime(131071) is True + assert is_mersenne_prime(2147483647) is True + + +def test_is_abundant(): + assert is_abundant(10) is False + assert is_abundant(12) is True + assert is_abundant(18) is True + assert is_abundant(21) is False + assert is_abundant(945) is True + + +def test_is_deficient(): + assert is_deficient(10) is True + assert is_deficient(22) is True + assert is_deficient(56) is False + assert is_deficient(20) is False + assert is_deficient(36) is False + + +def test_is_amicable(): + assert is_amicable(173, 129) is False + assert is_amicable(220, 284) is True + assert is_amicable(8756, 8756) is False + +def test_dra(): + assert dra(19, 12) == 8 + assert dra(2718, 10) == 9 + assert dra(0, 22) == 0 + assert dra(23456789, 10) == 8 + raises(ValueError, lambda: dra(24, -2)) + raises(ValueError, lambda: dra(24.2, 5)) + +def test_drm(): + assert drm(19, 12) == 7 + assert drm(2718, 10) == 2 + assert drm(0, 15) == 0 + assert drm(234161, 10) == 6 + raises(ValueError, lambda: drm(24, -2)) + raises(ValueError, lambda: drm(11.6, 9)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..80a5dfda389e7595b666e11b97e608786f239df5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py @@ -0,0 +1,250 @@ +from sympy.core.numbers import (I, Rational, nan, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.ntheory.generate import (sieve, Sieve) +from sympy.series.limits import limit + +from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \ + primerange, primepi, prime, primorial, composite, compositepi, reduced_totient +from sympy.ntheory.generate import cycle_length +from sympy.ntheory.primetest import mr +from sympy.testing.pytest import raises + +def test_prime(): + assert prime(1) == 2 + assert prime(2) == 3 + assert prime(5) == 11 + assert prime(11) == 31 + assert prime(57) == 269 + assert prime(296) == 1949 + assert prime(559) == 4051 + assert prime(3000) == 27449 + assert prime(4096) == 38873 + assert prime(9096) == 94321 + assert prime(25023) == 287341 + assert prime(10000000) == 179424673 # issue #20951 + assert prime(99999999) == 2038074739 + raises(ValueError, lambda: prime(0)) + sieve.extend(3000) + assert prime(401) == 2749 + raises(ValueError, lambda: prime(-1)) + + +def test_primepi(): + assert primepi(-1) == 0 + assert primepi(1) == 0 + assert primepi(2) == 1 + assert primepi(Rational(7, 2)) == 2 + assert primepi(3.5) == 2 + assert primepi(5) == 3 + assert primepi(11) == 5 + assert primepi(57) == 16 + assert primepi(296) == 62 + assert primepi(559) == 102 + assert primepi(3000) == 430 + assert primepi(4096) == 564 + assert primepi(9096) == 1128 + assert primepi(25023) == 2763 + assert primepi(10**8) == 5761455 + assert primepi(253425253) == 13856396 + assert primepi(8769575643) == 401464322 + sieve.extend(3000) + assert primepi(2000) == 303 + + n = Symbol('n') + assert primepi(n).subs(n, 2) == 1 + + r = Symbol('r', real=True) + assert primepi(r).subs(r, 2) == 1 + + assert primepi(S.Infinity) is S.Infinity + assert primepi(S.NegativeInfinity) == 0 + + assert limit(primepi(n), n, 100) == 25 + + raises(ValueError, lambda: primepi(I)) + raises(ValueError, lambda: primepi(1 + I)) + raises(ValueError, lambda: primepi(zoo)) + raises(ValueError, lambda: primepi(nan)) + + +def test_composite(): + from sympy.ntheory.generate import sieve + sieve._reset() + assert composite(1) == 4 + assert composite(2) == 6 + assert composite(5) == 10 + assert composite(11) == 20 + assert composite(41) == 58 + assert composite(57) == 80 + assert composite(296) == 370 + assert composite(559) == 684 + assert composite(3000) == 3488 + assert composite(4096) == 4736 + assert composite(9096) == 10368 + assert composite(25023) == 28088 + sieve.extend(3000) + assert composite(1957) == 2300 + assert composite(2568) == 2998 + raises(ValueError, lambda: composite(0)) + + +def test_compositepi(): + assert compositepi(1) == 0 + assert compositepi(2) == 0 + assert compositepi(5) == 1 + assert compositepi(11) == 5 + assert compositepi(57) == 40 + assert compositepi(296) == 233 + assert compositepi(559) == 456 + assert compositepi(3000) == 2569 + assert compositepi(4096) == 3531 + assert compositepi(9096) == 7967 + assert compositepi(25023) == 22259 + assert compositepi(10**8) == 94238544 + assert compositepi(253425253) == 239568856 + assert compositepi(8769575643) == 8368111320 + sieve.extend(3000) + assert compositepi(2321) == 1976 + + +def test_generate(): + from sympy.ntheory.generate import sieve + sieve._reset() + assert nextprime(-4) == 2 + assert nextprime(2) == 3 + assert nextprime(5) == 7 + assert nextprime(12) == 13 + assert prevprime(3) == 2 + assert prevprime(7) == 5 + assert prevprime(13) == 11 + assert prevprime(19) == 17 + assert prevprime(20) == 19 + + sieve.extend_to_no(9) + assert sieve._list[-1] == 23 + + assert sieve._list[-1] < 31 + assert 31 in sieve + + assert nextprime(90) == 97 + assert nextprime(10**40) == (10**40 + 121) + assert prevprime(97) == 89 + assert prevprime(10**40) == (10**40 - 17) + + assert list(sieve.primerange(10, 1)) == [] + assert list(sieve.primerange(5, 9)) == [5, 7] + sieve._reset(prime=True) + assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11] + assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11] + assert list(sieve.primerange(8)) == [2, 3, 5, 7] + assert list(sieve.primerange(-2)) == [] + assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23] + assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + + assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6] + sieve._reset(totient=True) + assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4] + assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)] + assert list(sieve.totientrange(0, 1)) == [] + assert list(sieve.totientrange(1, 2)) == [1] + + assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1] + sieve._reset(mobius=True) + assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0] + assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)] + assert list(sieve.mobiusrange(0, 1)) == [] + assert list(sieve.mobiusrange(1, 2)) == [1] + + assert list(primerange(10, 1)) == [] + assert list(primerange(2, 7)) == [2, 3, 5] + assert list(primerange(2, 10)) == [2, 3, 5, 7] + assert list(primerange(1050, 1100)) == [1051, 1061, + 1063, 1069, 1087, 1091, 1093, 1097] + s = Sieve() + for i in range(30, 2350, 376): + for j in range(2, 5096, 1139): + A = list(s.primerange(i, i + j)) + B = list(primerange(i, i + j)) + assert A == B + s = Sieve() + assert s[10] == 29 + + assert nextprime(2, 2) == 5 + + raises(ValueError, lambda: totient(0)) + + raises(ValueError, lambda: reduced_totient(0)) + + raises(ValueError, lambda: primorial(0)) + + assert mr(1, [2]) is False + + func = lambda i: (i**2 + 1) % 51 + assert next(cycle_length(func, 4)) == (6, 2) + assert list(cycle_length(func, 4, values=True)) == \ + [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] + assert next(cycle_length(func, 4, nmax=5)) == (5, None) + assert list(cycle_length(func, 4, nmax=5, values=True)) == \ + [17, 35, 2, 5, 26] + sieve.extend(3000) + assert nextprime(2968) == 2969 + assert prevprime(2930) == 2927 + raises(ValueError, lambda: prevprime(1)) + raises(ValueError, lambda: prevprime(-4)) + + +def test_randprime(): + assert randprime(10, 1) is None + assert randprime(3, -3) is None + assert randprime(2, 3) == 2 + assert randprime(1, 3) == 2 + assert randprime(3, 5) == 3 + raises(ValueError, lambda: randprime(-12, -2)) + raises(ValueError, lambda: randprime(-10, 0)) + raises(ValueError, lambda: randprime(20, 22)) + raises(ValueError, lambda: randprime(0, 2)) + raises(ValueError, lambda: randprime(1, 2)) + for a in [100, 300, 500, 250000]: + for b in [100, 300, 500, 250000]: + p = randprime(a, a + b) + assert a <= p < (a + b) and isprime(p) + + +def test_primorial(): + assert primorial(1) == 2 + assert primorial(1, nth=0) == 1 + assert primorial(2) == 6 + assert primorial(2, nth=0) == 2 + assert primorial(4, nth=0) == 6 + + +def test_search(): + assert 2 in sieve + assert 2.1 not in sieve + assert 1 not in sieve + assert 2**1000 not in sieve + raises(ValueError, lambda: sieve.search(1)) + + +def test_sieve_slice(): + assert sieve[5] == 11 + assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)] + assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)] + assert list(sieve[1:5]) == [2, 3, 5, 7] + raises(IndexError, lambda: sieve[:5]) + raises(IndexError, lambda: sieve[0]) + raises(IndexError, lambda: sieve[0:5]) + +def test_sieve_iter(): + values = [] + for value in sieve: + if value > 7: + break + values.append(value) + assert values == list(sieve[1:5]) + + +def test_sieve_repr(): + assert "sieve" in repr(sieve) + assert "prime" in repr(sieve) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py new file mode 100644 index 0000000000000000000000000000000000000000..10ebb1d3d3bdf5f736a6229579ae4c42a805745e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py @@ -0,0 +1,34 @@ +from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence +from sympy.testing.pytest import raises + + +def test_crt(): + def mcrt(m, v, r, symmetric=False): + assert crt(m, v, symmetric)[0] == r + mm, e, s = crt1(m) + assert crt2(m, v, mm, e, s, symmetric) == (r, mm) + + mcrt([2, 3, 5], [0, 0, 0], 0) + mcrt([2, 3, 5], [1, 1, 1], 1) + + mcrt([2, 3, 5], [-1, -1, -1], -1, True) + mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False) + + assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800) + + +def test_modular(): + assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140) + assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None + assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547) + assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547) + assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None + assert solve_congruence( + *list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547) + assert solve_congruence( + *list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094) + assert solve_congruence( + *list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094) + assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None + raises( + ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17])))) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..b455c5cc979b9ba9756c9da88c1694471115cd5d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py @@ -0,0 +1,48 @@ +from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients) +from sympy.ntheory.multinomial import multinomial_coefficients_iterator + + +def test_binomial_coefficients_list(): + assert binomial_coefficients_list(0) == [1] + assert binomial_coefficients_list(1) == [1, 1] + assert binomial_coefficients_list(2) == [1, 2, 1] + assert binomial_coefficients_list(3) == [1, 3, 3, 1] + assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1] + assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1] + assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1] + + +def test_binomial_coefficients(): + for n in range(15): + c = binomial_coefficients(n) + l = [c[k] for k in sorted(c)] + assert l == binomial_coefficients_list(n) + + +def test_multinomial_coefficients(): + assert multinomial_coefficients(1, 1) == {(1,): 1} + assert multinomial_coefficients(1, 2) == {(2,): 1} + assert multinomial_coefficients(1, 3) == {(3,): 1} + assert multinomial_coefficients(2, 0) == {(0, 0): 1} + assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1} + assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2} + assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1, + (2, 1): 3} + assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1, + (0, 0, 1): 1} + assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1, + (1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1} + mc = multinomial_coefficients(3, 3) + assert mc == {(2, 1, 0): 3, (0, 3, 0): 1, + (1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1, + (2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1} + assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1} + assert dict( + multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1} + assert dict(multinomial_coefficients_iterator(2, 2)) == \ + {(2, 0): 1, (0, 2): 1, (1, 1): 2} + assert dict(multinomial_coefficients_iterator(3, 3)) == mc + it = multinomial_coefficients_iterator(7, 2) + assert [next(it) for i in range(4)] == \ + [((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2), + ((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)] diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..1a347899c2efc8ae2b8a417dbb422a83cd529c61 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py @@ -0,0 +1,12 @@ +from sympy.ntheory import npartitions + + +def test_partitions(): + assert [npartitions(k) for k in range(13)] == \ + [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77] + assert npartitions(100) == 190569292 + assert npartitions(200) == 3972999029388 + assert npartitions(1000) == 24061467864032622473692149727991 + assert npartitions(2000) == 4720819175619413888601432406799959512200344166 + assert npartitions(10000) % 10**10 == 6916435144 + assert npartitions(100000) % 10**10 == 9421098519 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py new file mode 100644 index 0000000000000000000000000000000000000000..8817b645a0ffe1ccb35af9171d2234f9260b833c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py @@ -0,0 +1,159 @@ +from sympy.ntheory.generate import Sieve, sieve +from sympy.ntheory.primetest import (mr, is_lucas_prp, is_square, + is_strong_lucas_prp, is_extra_strong_lucas_prp, isprime, is_euler_pseudoprime, + is_gaussian_prime) + +from sympy.testing.pytest import slow +from sympy.core.numbers import I + +def test_euler_pseudoprimes(): + assert is_euler_pseudoprime(9, 1) == True + assert is_euler_pseudoprime(341, 2) == False + assert is_euler_pseudoprime(121, 3) == True + assert is_euler_pseudoprime(341, 4) == True + assert is_euler_pseudoprime(217, 5) == False + assert is_euler_pseudoprime(185, 6) == False + assert is_euler_pseudoprime(55, 111) == True + assert is_euler_pseudoprime(115, 114) == True + assert is_euler_pseudoprime(49, 117) == True + assert is_euler_pseudoprime(85, 84) == True + assert is_euler_pseudoprime(87, 88) == True + assert is_euler_pseudoprime(49, 128) == True + assert is_euler_pseudoprime(39, 77) == True + assert is_euler_pseudoprime(9881, 30) == True + assert is_euler_pseudoprime(8841, 29) == False + assert is_euler_pseudoprime(8421, 29) == False + assert is_euler_pseudoprime(9997, 19) == True + +def test_is_extra_strong_lucas_prp(): + assert is_extra_strong_lucas_prp(4) == False + assert is_extra_strong_lucas_prp(989) == True + assert is_extra_strong_lucas_prp(10877) == True + assert is_extra_strong_lucas_prp(9) == False + assert is_extra_strong_lucas_prp(16) == False + assert is_extra_strong_lucas_prp(169) == False + +@slow +def test_prps(): + oddcomposites = [n for n in range(1, 10**5) if + n % 2 and not isprime(n)] + # A checksum would be better. + assert sum(oddcomposites) == 2045603465 + assert [n for n in oddcomposites if mr(n, [2])] == [ + 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, + 52633, 65281, 74665, 80581, 85489, 88357, 90751] + assert [n for n in oddcomposites if mr(n, [3])] == [ + 121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531, + 18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139, + 74593, 79003, 82513, 87913, 88573, 97567] + assert [n for n in oddcomposites if mr(n, [325])] == [ + 9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059, + 2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911, + 12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649, + 24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041, + 55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641, + 76793, 78409, 85879] + assert not any(mr(n, [9345883071009581737]) for n in oddcomposites) + assert [n for n in oddcomposites if is_lucas_prp(n)] == [ + 323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877, + 11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971, + 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323, + 32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099, + 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377, + 63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799, + 82983, 84419, 86063, 90287, 94667, 97019, 97439] + assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [ + 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, + 58519, 75077, 97439] + assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n) + ] == [ + 989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, + 72389, 73919, 75077] + + +def test_isprime(): + s = Sieve() + s.extend(100000) + ps = set(s.primerange(2, 100001)) + for n in range(100001): + # if (n in ps) != isprime(n): print n + assert (n in ps) == isprime(n) + assert isprime(179424673) + assert isprime(20678048681) + assert isprime(1968188556461) + assert isprime(2614941710599) + assert isprime(65635624165761929287) + assert isprime(1162566711635022452267983) + assert isprime(77123077103005189615466924501) + assert isprime(3991617775553178702574451996736229) + assert isprime(273952953553395851092382714516720001799) + assert isprime(int(''' +531137992816767098689588206552468627329593117727031923199444138200403\ +559860852242739162502265229285668889329486246501015346579337652707239\ +409519978766587351943831270835393219031728127''')) + + # Some Mersenne primes + assert isprime(2**61 - 1) + assert isprime(2**89 - 1) + assert isprime(2**607 - 1) + # (but not all Mersenne's are primes + assert not isprime(2**601 - 1) + + # pseudoprimes + #------------- + # to some small bases + assert not isprime(2152302898747) + assert not isprime(3474749660383) + assert not isprime(341550071728321) + assert not isprime(3825123056546413051) + # passes the base set [2, 3, 7, 61, 24251] + assert not isprime(9188353522314541) + # large examples + assert not isprime(877777777777777777777777) + # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html + assert not isprime(318665857834031151167461) + # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html + assert not isprime(564132928021909221014087501701) + # Arnault's 1993 number; a factor of it is + # 400958216639499605418306452084546853005188166041132508774506\ + # 204738003217070119624271622319159721973358216316508535816696\ + # 9145233813917169287527980445796800452592031836601 + assert not isprime(int(''' +803837457453639491257079614341942108138837688287558145837488917522297\ +427376533365218650233616396004545791504202360320876656996676098728404\ +396540823292873879185086916685732826776177102938969773947016708230428\ +687109997439976544144845341155872450633409279022275296229414984230688\ +1685404326457534018329786111298960644845216191652872597534901''')) + # Arnault's 1995 number; can be factored as + # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is + # 296744956686855105501541746429053327307719917998530433509950\ + # 755312768387531717701995942385964281211880336647542183455624\ + # 93168782883 + assert not isprime(int(''' +288714823805077121267142959713039399197760945927972270092651602419743\ +230379915273311632898314463922594197780311092934965557841894944174093\ +380561511397999942154241693397290542371100275104208013496673175515285\ +922696291677532547504444585610194940420003990443211677661994962953925\ +045269871932907037356403227370127845389912612030924484149472897688540\ +6024976768122077071687938121709811322297802059565867''')) + sieve.extend(3000) + assert isprime(2819) + assert not isprime(2931) + assert not isprime(2.0) + + +def test_is_square(): + assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16] + + # issue #17044 + assert not is_square(60 ** 3) + assert not is_square(60 ** 5) + assert not is_square(84 ** 7) + assert not is_square(105 ** 9) + assert not is_square(120 ** 3) + +def test_is_gaussianprime(): + assert is_gaussian_prime(7*I) + assert is_gaussian_prime(7) + assert is_gaussian_prime(2 + 3*I) + assert not is_gaussian_prime(2 + 2*I) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py new file mode 100644 index 0000000000000000000000000000000000000000..19ee1782ce4658d48cf7f3451f15bec8e827b76a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +from sympy.ntheory import qs +from sympy.ntheory.qs import SievePolynomial, _generate_factor_base, \ + _initialize_first_polynomial, _initialize_ith_poly, \ + _gen_sieve_array, _check_smoothness, _trial_division_stage, _gauss_mod_2, \ + _build_matrix, _find_factor +from sympy.testing.pytest import slow + + +@slow +def test_qs_1(): + assert qs(10009202107, 100, 10000) == {100043, 100049} + assert qs(211107295182713951054568361, 1000, 10000) == \ + {13791315212531, 15307263442931} + assert qs(980835832582657*990377764891511, 3000, 50000) == \ + {980835832582657, 990377764891511} + assert qs(18640889198609*20991129234731, 1000, 50000) == \ + {18640889198609, 20991129234731} + + +def test_qs_2() -> None: + n = 10009202107 + M = 50 + # a = 10, b = 15, modified_coeff = [a**2, 2*a*b, b**2 - N] + sieve_poly = SievePolynomial([100, 1600, -10009195707], 10, 80) + assert sieve_poly.eval(10) == -10009169707 + assert sieve_poly.eval(5) == -10009185207 + + idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n) + assert idx_1000 == 82 + assert [factor_base[i].prime for i in range(15)] == \ + [2, 3, 7, 11, 17, 19, 29, 31, 43, 59, 61, 67, 71, 73, 79] + assert [factor_base[i].tmem_p for i in range(15)] == \ + [1, 1, 3, 5, 3, 6, 6, 14, 1, 16, 24, 22, 18, 22, 15] + assert [factor_base[i].log_p for i in range(5)] == \ + [710, 1125, 1993, 2455, 2901] + + g, B = _initialize_first_polynomial( + n, M, factor_base, idx_1000, idx_5000, seed=0) + assert g.a == 1133107 + assert g.b == 682543 + assert B == [272889, 409654] + assert [factor_base[i].soln1 for i in range(15)] == \ + [0, 0, 3, 7, 13, 0, 8, 19, 9, 43, 27, 25, 63, 29, 19] + assert [factor_base[i].soln2 for i in range(15)] == \ + [0, 1, 1, 3, 12, 16, 15, 6, 15, 1, 56, 55, 61, 58, 16] + assert [factor_base[i].a_inv for i in range(15)] == \ + [1, 1, 5, 7, 3, 5, 26, 6, 40, 5, 21, 45, 4, 1, 8] + assert [factor_base[i].b_ainv for i in range(5)] == \ + [[0, 0], [0, 2], [3, 0], [3, 9], [13, 13]] + + g_1 = _initialize_ith_poly(n, factor_base, 1, g, B) + assert g_1.a == 1133107 + assert g_1.b == 136765 + + sieve_array = _gen_sieve_array(M, factor_base) + assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710] + + assert _check_smoothness(9645, factor_base) == (5, False) + assert _check_smoothness(210313, factor_base)[0][0:15] == \ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] + assert _check_smoothness(210313, factor_base)[1] + + partial_relations: dict[int, tuple[int, int]] = {} + smooth_relation, partial_relation = _trial_division_stage( + n, M, factor_base, sieve_array, sieve_poly, partial_relations, + ERROR_TERM=25*2**10) + + assert partial_relations == { + 8699: (440, -10009008507), + 166741: (490, -10008962007), + 131449: (530, -10008921207), + 6653: (550, -10008899607) + } + assert [smooth_relation[i][0] for i in range(5)] == [ + -250, -670615476700, -45211565844500, -231723037747200, -1811665537200] + assert [smooth_relation[i][1] for i in range(5)] == [ + -10009139607, 1133094251961, 5302606761, 53804049849, 1950723889] + assert smooth_relation[0][2][0:15] == [ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + assert _gauss_mod_2( + [[0, 0, 1], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]] + ) == ( + [[[0, 1, 1], 3], [[0, 1, 1], 4]], + [True, True, True, False, False], + [[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 1, 1]] + ) + + +def test_qs_3(): + N = 1817 + smooth_relations = [ + (2455024, 637, [0, 0, 0, 1]), + (-27993000, 81536, [0, 1, 0, 1]), + (11461840, 12544, [0, 0, 0, 0]), + (149, 20384, [0, 1, 0, 1]), + (-31138074, 19208, [0, 1, 0, 0]) + ] + + matrix = _build_matrix(smooth_relations) + assert matrix == [ + [0, 0, 0, 1], + [0, 1, 0, 1], + [0, 0, 0, 0], + [0, 1, 0, 1], + [0, 1, 0, 0] + ] + + dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) + assert dependent_row == [[[0, 0, 0, 0], 2], [[0, 1, 0, 0], 3]] + assert mark == [True, True, False, False, True] + assert gauss_matrix == [ + [0, 0, 0, 1], + [0, 1, 0, 0], + [0, 0, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 1] + ] + + factor = _find_factor( + dependent_row, mark, gauss_matrix, 0, smooth_relations, N) + assert factor == 23 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py new file mode 100644 index 0000000000000000000000000000000000000000..06fff52d16acd9c79f86e0088ba7ad5d80a9cfc7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py @@ -0,0 +1,286 @@ +from collections import defaultdict +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) + +from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \ + legendre_symbol, jacobi_symbol, totient, primerange, sqrt_mod, \ + primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \ + sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, \ + polynomial_congruence +from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \ + _discrete_log_trial_mul, _discrete_log_shanks_steps, \ + _discrete_log_pollard_rho, _discrete_log_pohlig_hellman +from sympy.polys.domains import ZZ +from sympy.testing.pytest import raises + + +def test_residue(): + assert n_order(2, 13) == 12 + assert [n_order(a, 7) for a in range(1, 7)] == \ + [1, 3, 6, 3, 6, 2] + assert n_order(5, 17) == 16 + assert n_order(17, 11) == n_order(6, 11) + assert n_order(101, 119) == 6 + assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650 + raises(ValueError, lambda: n_order(6, 9)) + + assert is_primitive_root(2, 7) is False + assert is_primitive_root(3, 8) is False + assert is_primitive_root(11, 14) is False + assert is_primitive_root(12, 17) == is_primitive_root(29, 17) + raises(ValueError, lambda: is_primitive_root(3, 6)) + + for p in primerange(3, 100): + it = _primitive_root_prime_iter(p) + assert len(list(it)) == totient(totient(p)) + assert primitive_root(97) == 5 + assert primitive_root(97**2) == 5 + assert primitive_root(40487) == 5 + # note that primitive_root(40487) + 40487 = 40492 is a primitive root + # of 40487**2, but it is not the smallest + assert primitive_root(40487**2) == 10 + assert primitive_root(82) == 7 + p = 10**50 + 151 + assert primitive_root(p) == 11 + assert primitive_root(2*p) == 11 + assert primitive_root(p**2) == 11 + raises(ValueError, lambda: primitive_root(-3)) + + assert is_quad_residue(3, 7) is False + assert is_quad_residue(10, 13) is True + assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139) + assert is_quad_residue(207, 251) is True + assert is_quad_residue(0, 1) is True + assert is_quad_residue(1, 1) is True + assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True + assert is_quad_residue(1, 4) is True + assert is_quad_residue(2, 27) is False + assert is_quad_residue(13122380800, 13604889600) is True + assert [j for j in range(14) if is_quad_residue(j, 14)] == \ + [0, 1, 2, 4, 7, 8, 9, 11] + raises(ValueError, lambda: is_quad_residue(1.1, 2)) + raises(ValueError, lambda: is_quad_residue(2, 0)) + + assert quadratic_residues(S.One) == [0] + assert quadratic_residues(1) == [0] + assert quadratic_residues(12) == [0, 1, 4, 9] + assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12] + assert [len(quadratic_residues(i)) for i in range(1, 20)] == \ + [1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10] + + assert list(sqrt_mod_iter(6, 2)) == [0] + assert sqrt_mod(3, 13) == 4 + assert sqrt_mod(3, -13) == 4 + assert sqrt_mod(6, 23) == 11 + assert sqrt_mod(345, 690) == 345 + assert sqrt_mod(67, 101) == None + assert sqrt_mod(1020, 104729) == None + + for p in range(3, 100): + d = defaultdict(list) + for i in range(p): + d[pow(i, 2, p)].append(i) + for i in range(1, p): + it = sqrt_mod_iter(i, p) + v = sqrt_mod(i, p, True) + if v: + v = sorted(v) + assert d[i] == v + else: + assert not d[i] + + assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24] + assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78] + assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240] + assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72] + assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\ + 126, 144, 153, 171, 180, 198, 207, 225, 234] + assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\ + 333, 396, 414, 477, 495, 558, 576, 639, 657, 720] + assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\ + 981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178] + + for a, p in [(26214400, 32768000000), (26214400, 16384000000), + (262144, 1048576), (87169610025, 163443018796875), + (22315420166400, 167365651248000000)]: + assert pow(sqrt_mod(a, p), 2, p) == a + + n = 70 + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2) + it = sqrt_mod_iter(a, p) + for i in range(10): + assert pow(next(it), 2, p) == a + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3) + it = sqrt_mod_iter(a, p) + for i in range(2): + assert pow(next(it), 2, p) == a + n = 100 + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1) + it = sqrt_mod_iter(a, p) + for i in range(2): + assert pow(next(it), 2, p) == a + + assert type(next(sqrt_mod_iter(9, 27))) is int + assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1)) + assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1)) + + assert is_nthpow_residue(2, 1, 5) + + #issue 10816 + assert is_nthpow_residue(1, 0, 1) is False + assert is_nthpow_residue(1, 0, 2) is True + assert is_nthpow_residue(3, 0, 2) is True + assert is_nthpow_residue(0, 1, 8) is True + assert is_nthpow_residue(2, 3, 2) is True + assert is_nthpow_residue(2, 3, 9) is False + assert is_nthpow_residue(3, 5, 30) is True + assert is_nthpow_residue(21, 11, 20) is True + assert is_nthpow_residue(7, 10, 20) is False + assert is_nthpow_residue(5, 10, 20) is True + assert is_nthpow_residue(3, 10, 48) is False + assert is_nthpow_residue(1, 10, 40) is True + assert is_nthpow_residue(3, 10, 24) is False + assert is_nthpow_residue(1, 10, 24) is True + assert is_nthpow_residue(3, 10, 24) is False + assert is_nthpow_residue(2, 10, 48) is False + assert is_nthpow_residue(81, 3, 972) is False + assert is_nthpow_residue(243, 5, 5103) is True + assert is_nthpow_residue(243, 3, 1240029) is False + assert is_nthpow_residue(36010, 8, 87382) is True + assert is_nthpow_residue(28552, 6, 2218) is True + assert is_nthpow_residue(92712, 9, 50026) is True + x = {pow(i, 56, 1024) for i in range(1024)} + assert {a for a in range(1024) if is_nthpow_residue(a, 56, 1024)} == x + x = { pow(i, 256, 2048) for i in range(2048)} + assert {a for a in range(2048) if is_nthpow_residue(a, 256, 2048)} == x + x = { pow(i, 11, 324000) for i in range(1000)} + assert [ is_nthpow_residue(a, 11, 324000) for a in x] + x = { pow(i, 17, 22217575536) for i in range(1000)} + assert [ is_nthpow_residue(a, 17, 22217575536) for a in x] + assert is_nthpow_residue(676, 3, 5364) + assert is_nthpow_residue(9, 12, 36) + assert is_nthpow_residue(32, 10, 41) + assert is_nthpow_residue(4, 2, 64) + assert is_nthpow_residue(31, 4, 41) + assert not is_nthpow_residue(2, 2, 5) + assert is_nthpow_residue(8547, 12, 10007) + assert is_nthpow_residue(Dummy(even=True) + 3, 3, 2) == True + assert nthroot_mod(Dummy(odd=True), 3, 2) == 1 + + assert nthroot_mod(29, 31, 74) == [45] + assert nthroot_mod(1801, 11, 2663) == 44 + for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663), + (26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663), + (1714, 12, 2663), (28477, 9, 33343)]: + r = nthroot_mod(a, q, p) + assert pow(r, q, p) == a + assert nthroot_mod(11, 3, 109) is None + assert nthroot_mod(16, 5, 36, True) == [4, 22] + assert nthroot_mod(9, 16, 36, True) == [3, 9, 15, 21, 27, 33] + assert nthroot_mod(4, 3, 3249000) == [] + assert nthroot_mod(36010, 8, 87382, True) == [40208, 47174] + assert nthroot_mod(0, 12, 37, True) == [0] + assert nthroot_mod(0, 7, 100, True) == [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] + assert nthroot_mod(4, 4, 27, True) == [5, 22] + assert nthroot_mod(4, 4, 121, True) == [19, 102] + assert nthroot_mod(2, 3, 7, True) == [] + + for p in range(5, 100): + qv = range(3, p, 4) + for q in qv: + d = defaultdict(list) + for i in range(p): + d[pow(i, q, p)].append(i) + for a in range(1, p - 1): + res = nthroot_mod(a, q, p, True) + if d[a]: + assert d[a] == res + else: + assert res == [] + + assert legendre_symbol(5, 11) == 1 + assert legendre_symbol(25, 41) == 1 + assert legendre_symbol(67, 101) == -1 + assert legendre_symbol(0, 13) == 0 + assert legendre_symbol(9, 3) == 0 + raises(ValueError, lambda: legendre_symbol(2, 4)) + + assert jacobi_symbol(25, 41) == 1 + assert jacobi_symbol(-23, 83) == -1 + assert jacobi_symbol(3, 9) == 0 + assert jacobi_symbol(42, 97) == -1 + assert jacobi_symbol(3, 5) == -1 + assert jacobi_symbol(7, 9) == 1 + assert jacobi_symbol(0, 3) == 0 + assert jacobi_symbol(0, 1) == 1 + assert jacobi_symbol(2, 1) == 1 + assert jacobi_symbol(1, 3) == 1 + raises(ValueError, lambda: jacobi_symbol(3, 8)) + + assert mobius(13*7) == 1 + assert mobius(1) == 1 + assert mobius(13*7*5) == -1 + assert mobius(13**2) == 0 + raises(ValueError, lambda: mobius(-3)) + + p = Symbol('p', integer=True, positive=True, prime=True) + x = Symbol('x', positive=True) + i = Symbol('i', integer=True) + assert mobius(p) == -1 + raises(TypeError, lambda: mobius(x)) + raises(ValueError, lambda: mobius(i)) + + assert _discrete_log_trial_mul(587, 2**7, 2) == 7 + assert _discrete_log_trial_mul(941, 7**18, 7) == 18 + assert _discrete_log_trial_mul(389, 3**81, 3) == 81 + assert _discrete_log_trial_mul(191, 19**123, 19) == 123 + assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2 + assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19 + assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71 + assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321 + assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6 + assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19 + assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40 + assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333 + raises(ValueError, lambda: _discrete_log_pollard_rho(11, 7, 31, rseed=0)) + raises(ValueError, lambda: _discrete_log_pollard_rho(227, 3**7, 5, rseed=0)) + + assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9 + assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31 + assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98 + assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444 + assert discrete_log(587, 2**9, 2) == 9 + assert discrete_log(2456747, 3**51, 3) == 51 + assert discrete_log(32942478, 11**127, 11) == 127 + assert discrete_log(432751500361, 7**324, 7) == 324 + args = 5779, 3528, 6215 + assert discrete_log(*args) == 687 + assert discrete_log(*Tuple(*args)) == 687 + assert quadratic_congruence(400, 85, 125, 1600) == [295, 615, 935, 1255, 1575] + assert quadratic_congruence(3, 6, 5, 25) == [3, 20] + assert quadratic_congruence(120, 80, 175, 500) == [] + assert quadratic_congruence(15, 14, 7, 2) == [1] + assert quadratic_congruence(8, 15, 7, 29) == [10, 28] + assert quadratic_congruence(160, 200, 300, 461) == [144, 431] + assert quadratic_congruence(100000, 123456, 7415263, 48112959837082048697) == [30417843635344493501, 36001135160550533083] + assert quadratic_congruence(65, 121, 72, 277) == [249, 252] + assert quadratic_congruence(5, 10, 14, 2) == [0] + assert quadratic_congruence(10, 17, 19, 2) == [1] + assert quadratic_congruence(10, 14, 20, 2) == [0, 1] + assert polynomial_congruence(6*x**5 + 10*x**4 + 5*x**3 + x**2 + x + 1, + 972000) == [220999, 242999, 463999, 485999, 706999, 728999, 949999, 971999] + + assert polynomial_congruence(x**3 - 10*x**2 + 12*x - 82, 33075) == [30287] + assert polynomial_congruence(x**2 + x + 47, 2401) == [785, 1615] + assert polynomial_congruence(10*x**2 + 14*x + 20, 2) == [0, 1] + assert polynomial_congruence(x**3 + 3, 16) == [5] + assert polynomial_congruence(65*x**2 + 121*x + 72, 277) == [249, 252] + assert polynomial_congruence(x**4 - 4, 27) == [5, 22] + assert polynomial_congruence(35*x**3 - 6*x**2 - 567*x + 2308, 148225) == [86957, + 111157, 122531, 146731] + assert polynomial_congruence(x**16 - 9, 36) == [3, 9, 15, 21, 27, 33] + assert polynomial_congruence(x**6 - 2*x**5 - 35, 6125) == [3257] + raises(ValueError, lambda: polynomial_congruence(x**x, 6125)) + raises(ValueError, lambda: polynomial_congruence(x**i, 6125)) + raises(ValueError, lambda: polynomial_congruence(0.1*x**2 + 6, 100)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f38ac72dfc8f4d292e1cc45f44f7a7090ab7190 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08efef6cd131f51c66cf407c97535e9805efee1e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad15cf710bc34426ea01a127c004841e12f46f30 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f40a09e1cc323da8608c51b586cacbcb656ef951 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fdf74cb4ef8750893c95628d5ab35e3eb8de23f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a9322ffa2fe1e52e3d69ace7fb028716f590d46 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0f80dcde52a561415ff5e62a020b760ac830210 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d82d07d70de6491227b3dc2059ad01ea3fbfbd52 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25d41aeb251cbc32490b4d7b05e41a9063c0f1df Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6be644d157a00df806572533819657ed396dfff5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c25e1622cdbb0f9b5bd77ef8b33873c7e6dcb01b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0440ff6b90c138bc94ec3e544d7b1df0d5270808 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94e3d87ce8ddeeb7bd475401eedfd6d2e8aeaaea Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4604ed78d0a91328db57baeca80de8081a1b8df1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08eeee35df2a583d483df8c16f798d40bd98d1d1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9feea96d465392fa52ce2a047f0a7cb581469956 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b0e596f765ad4e800528276e8e7be001eeacec7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c99d6203c55f5bf5a03569cf1868897496a4e63f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb73840d15595e206d9e0da3c3f1ca5c98c28cad Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6916ff6aced2ce126668324a9fc6874ebb499b8f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77b7565f486d5849efcd2fa4529ae6d8f917020a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75a5527771310d48e357c4351c13f5b7e1b4b31 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ce64bd09cf33b2d3c17e2bae7a0b4fc817755f6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f8bf2f9ba59ab9e0fac102e2ba0c523e9a2e74d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-310.pyc differ