Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__init__.py +25 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/euler.py +108 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/singularities.py +406 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc +3 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc +3 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/digits.py +150 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/ecm.py +345 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/generate.py +1147 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/primetest.py +793 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/qs.py +511 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py +1954 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py +134 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py +55 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_hypothesis.py +24 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/aesaracode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/c.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/codeprinter.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/conventions.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/cxx.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/defaults.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/dot.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/fortran.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/glsl.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/gtk.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/jscode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/julia.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/lambdarepr.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/llvmjitcode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/maple.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/mathematica.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/mathml.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/numpy.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/octave.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/precedence.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/preview.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/printer.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/pycode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/python.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/rcode.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/repr.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/rust.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/smtlib.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/str.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -870,3 +870,5 @@ evalkit_tf437/lib/python3.10/site-packages/triton/_C/libtriton.so filter=lfs dif
|
|
| 870 |
infer_4_47_1/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 871 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 872 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 870 |
infer_4_47_1/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 871 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 872 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 873 |
+
infer_4_47_1/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 874 |
+
infer_4_47_1/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calculus-related methods."""
|
| 2 |
+
|
| 3 |
+
from .euler import euler_equations
|
| 4 |
+
from .singularities import (singularities, is_increasing,
|
| 5 |
+
is_strictly_increasing, is_decreasing,
|
| 6 |
+
is_strictly_decreasing, is_monotonic)
|
| 7 |
+
from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite
|
| 8 |
+
from .util import (periodicity, not_empty_in, is_convex,
|
| 9 |
+
stationary_points, minimum, maximum)
|
| 10 |
+
from .accumulationbounds import AccumBounds
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
'euler_equations',
|
| 14 |
+
|
| 15 |
+
'singularities', 'is_increasing',
|
| 16 |
+
'is_strictly_increasing', 'is_decreasing',
|
| 17 |
+
'is_strictly_decreasing', 'is_monotonic',
|
| 18 |
+
|
| 19 |
+
'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite',
|
| 20 |
+
|
| 21 |
+
'periodicity', 'not_empty_in', 'is_convex', 'stationary_points',
|
| 22 |
+
'minimum', 'maximum',
|
| 23 |
+
|
| 24 |
+
'AccumBounds'
|
| 25 |
+
]
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/euler.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements a method to find
|
| 3 |
+
Euler-Lagrange Equations for given Lagrangian.
|
| 4 |
+
"""
|
| 5 |
+
from itertools import combinations_with_replacement
|
| 6 |
+
from sympy.core.function import (Derivative, Function, diff)
|
| 7 |
+
from sympy.core.relational import Eq
|
| 8 |
+
from sympy.core.singleton import S
|
| 9 |
+
from sympy.core.symbol import Symbol
|
| 10 |
+
from sympy.core.sympify import sympify
|
| 11 |
+
from sympy.utilities.iterables import iterable
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def euler_equations(L, funcs=(), vars=()):
|
| 15 |
+
r"""
|
| 16 |
+
Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
==========
|
| 20 |
+
|
| 21 |
+
L : Expr
|
| 22 |
+
The Lagrangian that should be a function of the functions listed
|
| 23 |
+
in the second argument and their derivatives.
|
| 24 |
+
|
| 25 |
+
For example, in the case of two functions $f(x,y)$, $g(x,y)$ and
|
| 26 |
+
two independent variables $x$, $y$ the Lagrangian has the form:
|
| 27 |
+
|
| 28 |
+
.. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x},
|
| 29 |
+
\frac{\partial f(x,y)}{\partial y},
|
| 30 |
+
\frac{\partial g(x,y)}{\partial x},
|
| 31 |
+
\frac{\partial g(x,y)}{\partial y},x,y\right)
|
| 32 |
+
|
| 33 |
+
In many cases it is not necessary to provide anything, except the
|
| 34 |
+
Lagrangian, it will be auto-detected (and an error raised if this
|
| 35 |
+
cannot be done).
|
| 36 |
+
|
| 37 |
+
funcs : Function or an iterable of Functions
|
| 38 |
+
The functions that the Lagrangian depends on. The Euler equations
|
| 39 |
+
are differential equations for each of these functions.
|
| 40 |
+
|
| 41 |
+
vars : Symbol or an iterable of Symbols
|
| 42 |
+
The Symbols that are the independent variables of the functions.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
=======
|
| 46 |
+
|
| 47 |
+
eqns : list of Eq
|
| 48 |
+
The list of differential equations, one for each function.
|
| 49 |
+
|
| 50 |
+
Examples
|
| 51 |
+
========
|
| 52 |
+
|
| 53 |
+
>>> from sympy import euler_equations, Symbol, Function
|
| 54 |
+
>>> x = Function('x')
|
| 55 |
+
>>> t = Symbol('t')
|
| 56 |
+
>>> L = (x(t).diff(t))**2/2 - x(t)**2/2
|
| 57 |
+
>>> euler_equations(L, x(t), t)
|
| 58 |
+
[Eq(-x(t) - Derivative(x(t), (t, 2)), 0)]
|
| 59 |
+
>>> u = Function('u')
|
| 60 |
+
>>> x = Symbol('x')
|
| 61 |
+
>>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2
|
| 62 |
+
>>> euler_equations(L, u(t, x), [t, x])
|
| 63 |
+
[Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)]
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
==========
|
| 67 |
+
|
| 68 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
funcs = tuple(funcs) if iterable(funcs) else (funcs,)
|
| 73 |
+
|
| 74 |
+
if not funcs:
|
| 75 |
+
funcs = tuple(L.atoms(Function))
|
| 76 |
+
else:
|
| 77 |
+
for f in funcs:
|
| 78 |
+
if not isinstance(f, Function):
|
| 79 |
+
raise TypeError('Function expected, got: %s' % f)
|
| 80 |
+
|
| 81 |
+
vars = tuple(vars) if iterable(vars) else (vars,)
|
| 82 |
+
|
| 83 |
+
if not vars:
|
| 84 |
+
vars = funcs[0].args
|
| 85 |
+
else:
|
| 86 |
+
vars = tuple(sympify(var) for var in vars)
|
| 87 |
+
|
| 88 |
+
if not all(isinstance(v, Symbol) for v in vars):
|
| 89 |
+
raise TypeError('Variables are not symbols, got %s' % vars)
|
| 90 |
+
|
| 91 |
+
for f in funcs:
|
| 92 |
+
if not vars == f.args:
|
| 93 |
+
raise ValueError("Variables %s do not match args: %s" % (vars, f))
|
| 94 |
+
|
| 95 |
+
order = max([len(d.variables) for d in L.atoms(Derivative)
|
| 96 |
+
if d.expr in funcs] + [0])
|
| 97 |
+
|
| 98 |
+
eqns = []
|
| 99 |
+
for f in funcs:
|
| 100 |
+
eq = diff(L, f)
|
| 101 |
+
for i in range(1, order + 1):
|
| 102 |
+
for p in combinations_with_replacement(vars, i):
|
| 103 |
+
eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p)
|
| 104 |
+
new_eq = Eq(eq, 0)
|
| 105 |
+
if isinstance(new_eq, Eq):
|
| 106 |
+
eqns.append(new_eq)
|
| 107 |
+
|
| 108 |
+
return eqns
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/singularities.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Singularities
|
| 3 |
+
=============
|
| 4 |
+
|
| 5 |
+
This module implements algorithms for finding singularities for a function
|
| 6 |
+
and identifying types of functions.
|
| 7 |
+
|
| 8 |
+
The differential calculus methods in this module include methods to identify
|
| 9 |
+
the following function types in the given ``Interval``:
|
| 10 |
+
- Increasing
|
| 11 |
+
- Strictly Increasing
|
| 12 |
+
- Decreasing
|
| 13 |
+
- Strictly Decreasing
|
| 14 |
+
- Monotonic
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from sympy.core.power import Pow
|
| 19 |
+
from sympy.core.singleton import S
|
| 20 |
+
from sympy.core.symbol import Symbol
|
| 21 |
+
from sympy.core.sympify import sympify
|
| 22 |
+
from sympy.functions.elementary.exponential import log
|
| 23 |
+
from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos
|
| 24 |
+
from sympy.functions.elementary.hyperbolic import (
|
| 25 |
+
sech, csch, coth, tanh, cosh, asech, acsch, atanh, acoth)
|
| 26 |
+
from sympy.utilities.misc import filldedent
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def singularities(expression, symbol, domain=None):
|
| 30 |
+
"""
|
| 31 |
+
Find singularities of a given function.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
==========
|
| 35 |
+
|
| 36 |
+
expression : Expr
|
| 37 |
+
The target function in which singularities need to be found.
|
| 38 |
+
symbol : Symbol
|
| 39 |
+
The symbol over the values of which the singularity in
|
| 40 |
+
expression in being searched for.
|
| 41 |
+
|
| 42 |
+
Returns
|
| 43 |
+
=======
|
| 44 |
+
|
| 45 |
+
Set
|
| 46 |
+
A set of values for ``symbol`` for which ``expression`` has a
|
| 47 |
+
singularity. An ``EmptySet`` is returned if ``expression`` has no
|
| 48 |
+
singularities for any given value of ``Symbol``.
|
| 49 |
+
|
| 50 |
+
Raises
|
| 51 |
+
======
|
| 52 |
+
|
| 53 |
+
NotImplementedError
|
| 54 |
+
Methods for determining the singularities of this function have
|
| 55 |
+
not been developed.
|
| 56 |
+
|
| 57 |
+
Notes
|
| 58 |
+
=====
|
| 59 |
+
|
| 60 |
+
This function does not find non-isolated singularities
|
| 61 |
+
nor does it find branch points of the expression.
|
| 62 |
+
|
| 63 |
+
Currently supported functions are:
|
| 64 |
+
- univariate continuous (real or complex) functions
|
| 65 |
+
|
| 66 |
+
References
|
| 67 |
+
==========
|
| 68 |
+
|
| 69 |
+
.. [1] https://en.wikipedia.org/wiki/Mathematical_singularity
|
| 70 |
+
|
| 71 |
+
Examples
|
| 72 |
+
========
|
| 73 |
+
|
| 74 |
+
>>> from sympy import singularities, Symbol, log
|
| 75 |
+
>>> x = Symbol('x', real=True)
|
| 76 |
+
>>> y = Symbol('y', real=False)
|
| 77 |
+
>>> singularities(x**2 + x + 1, x)
|
| 78 |
+
EmptySet
|
| 79 |
+
>>> singularities(1/(x + 1), x)
|
| 80 |
+
{-1}
|
| 81 |
+
>>> singularities(1/(y**2 + 1), y)
|
| 82 |
+
{-I, I}
|
| 83 |
+
>>> singularities(1/(y**3 + 1), y)
|
| 84 |
+
{-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2}
|
| 85 |
+
>>> singularities(log(x), x)
|
| 86 |
+
{0}
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
from sympy.solvers.solveset import solveset
|
| 90 |
+
|
| 91 |
+
if domain is None:
|
| 92 |
+
domain = S.Reals if symbol.is_real else S.Complexes
|
| 93 |
+
try:
|
| 94 |
+
sings = S.EmptySet
|
| 95 |
+
e = expression.rewrite([sec, csc, cot, tan], cos)
|
| 96 |
+
e = e.rewrite([sech, csch, coth, tanh], cosh)
|
| 97 |
+
for i in e.atoms(Pow):
|
| 98 |
+
if i.exp.is_infinite:
|
| 99 |
+
raise NotImplementedError
|
| 100 |
+
if i.exp.is_negative:
|
| 101 |
+
# XXX: exponent of varying sign not handled
|
| 102 |
+
sings += solveset(i.base, symbol, domain)
|
| 103 |
+
for i in expression.atoms(log, asech, acsch):
|
| 104 |
+
sings += solveset(i.args[0], symbol, domain)
|
| 105 |
+
for i in expression.atoms(atanh, acoth):
|
| 106 |
+
sings += solveset(i.args[0] - 1, symbol, domain)
|
| 107 |
+
sings += solveset(i.args[0] + 1, symbol, domain)
|
| 108 |
+
return sings
|
| 109 |
+
except NotImplementedError:
|
| 110 |
+
raise NotImplementedError(filldedent('''
|
| 111 |
+
Methods for determining the singularities
|
| 112 |
+
of this function have not been developed.'''))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
###########################################################################
|
| 116 |
+
# DIFFERENTIAL CALCULUS METHODS #
|
| 117 |
+
###########################################################################
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None):
|
| 121 |
+
"""
|
| 122 |
+
Helper function for functions checking function monotonicity.
|
| 123 |
+
|
| 124 |
+
Parameters
|
| 125 |
+
==========
|
| 126 |
+
|
| 127 |
+
expression : Expr
|
| 128 |
+
The target function which is being checked
|
| 129 |
+
predicate : function
|
| 130 |
+
The property being tested for. The function takes in an integer
|
| 131 |
+
and returns a boolean. The integer input is the derivative and
|
| 132 |
+
the boolean result should be true if the property is being held,
|
| 133 |
+
and false otherwise.
|
| 134 |
+
interval : Set, optional
|
| 135 |
+
The range of values in which we are testing, defaults to all reals.
|
| 136 |
+
symbol : Symbol, optional
|
| 137 |
+
The symbol present in expression which gets varied over the given range.
|
| 138 |
+
|
| 139 |
+
It returns a boolean indicating whether the interval in which
|
| 140 |
+
the function's derivative satisfies given predicate is a superset
|
| 141 |
+
of the given interval.
|
| 142 |
+
|
| 143 |
+
Returns
|
| 144 |
+
=======
|
| 145 |
+
|
| 146 |
+
Boolean
|
| 147 |
+
True if ``predicate`` is true for all the derivatives when ``symbol``
|
| 148 |
+
is varied in ``range``, False otherwise.
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
from sympy.solvers.solveset import solveset
|
| 152 |
+
|
| 153 |
+
expression = sympify(expression)
|
| 154 |
+
free = expression.free_symbols
|
| 155 |
+
|
| 156 |
+
if symbol is None:
|
| 157 |
+
if len(free) > 1:
|
| 158 |
+
raise NotImplementedError(
|
| 159 |
+
'The function has not yet been implemented'
|
| 160 |
+
' for all multivariate expressions.'
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
variable = symbol or (free.pop() if free else Symbol('x'))
|
| 164 |
+
derivative = expression.diff(variable)
|
| 165 |
+
predicate_interval = solveset(predicate(derivative), variable, S.Reals)
|
| 166 |
+
return interval.is_subset(predicate_interval)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def is_increasing(expression, interval=S.Reals, symbol=None):
|
| 170 |
+
"""
|
| 171 |
+
Return whether the function is increasing in the given interval.
|
| 172 |
+
|
| 173 |
+
Parameters
|
| 174 |
+
==========
|
| 175 |
+
|
| 176 |
+
expression : Expr
|
| 177 |
+
The target function which is being checked.
|
| 178 |
+
interval : Set, optional
|
| 179 |
+
The range of values in which we are testing (defaults to set of
|
| 180 |
+
all real numbers).
|
| 181 |
+
symbol : Symbol, optional
|
| 182 |
+
The symbol present in expression which gets varied over the given range.
|
| 183 |
+
|
| 184 |
+
Returns
|
| 185 |
+
=======
|
| 186 |
+
|
| 187 |
+
Boolean
|
| 188 |
+
True if ``expression`` is increasing (either strictly increasing or
|
| 189 |
+
constant) in the given ``interval``, False otherwise.
|
| 190 |
+
|
| 191 |
+
Examples
|
| 192 |
+
========
|
| 193 |
+
|
| 194 |
+
>>> from sympy import is_increasing
|
| 195 |
+
>>> from sympy.abc import x, y
|
| 196 |
+
>>> from sympy import S, Interval, oo
|
| 197 |
+
>>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
|
| 198 |
+
True
|
| 199 |
+
>>> is_increasing(-x**2, Interval(-oo, 0))
|
| 200 |
+
True
|
| 201 |
+
>>> is_increasing(-x**2, Interval(0, oo))
|
| 202 |
+
False
|
| 203 |
+
>>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
|
| 204 |
+
False
|
| 205 |
+
>>> is_increasing(x**2 + y, Interval(1, 2), x)
|
| 206 |
+
True
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def is_strictly_increasing(expression, interval=S.Reals, symbol=None):
|
| 213 |
+
"""
|
| 214 |
+
Return whether the function is strictly increasing in the given interval.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
==========
|
| 218 |
+
|
| 219 |
+
expression : Expr
|
| 220 |
+
The target function which is being checked.
|
| 221 |
+
interval : Set, optional
|
| 222 |
+
The range of values in which we are testing (defaults to set of
|
| 223 |
+
all real numbers).
|
| 224 |
+
symbol : Symbol, optional
|
| 225 |
+
The symbol present in expression which gets varied over the given range.
|
| 226 |
+
|
| 227 |
+
Returns
|
| 228 |
+
=======
|
| 229 |
+
|
| 230 |
+
Boolean
|
| 231 |
+
True if ``expression`` is strictly increasing in the given ``interval``,
|
| 232 |
+
False otherwise.
|
| 233 |
+
|
| 234 |
+
Examples
|
| 235 |
+
========
|
| 236 |
+
|
| 237 |
+
>>> from sympy import is_strictly_increasing
|
| 238 |
+
>>> from sympy.abc import x, y
|
| 239 |
+
>>> from sympy import Interval, oo
|
| 240 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
|
| 241 |
+
True
|
| 242 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
|
| 243 |
+
True
|
| 244 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
|
| 245 |
+
False
|
| 246 |
+
>>> is_strictly_increasing(-x**2, Interval(0, oo))
|
| 247 |
+
False
|
| 248 |
+
>>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x)
|
| 249 |
+
False
|
| 250 |
+
|
| 251 |
+
"""
|
| 252 |
+
return monotonicity_helper(expression, lambda x: x > 0, interval, symbol)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def is_decreasing(expression, interval=S.Reals, symbol=None):
|
| 256 |
+
"""
|
| 257 |
+
Return whether the function is decreasing in the given interval.
|
| 258 |
+
|
| 259 |
+
Parameters
|
| 260 |
+
==========
|
| 261 |
+
|
| 262 |
+
expression : Expr
|
| 263 |
+
The target function which is being checked.
|
| 264 |
+
interval : Set, optional
|
| 265 |
+
The range of values in which we are testing (defaults to set of
|
| 266 |
+
all real numbers).
|
| 267 |
+
symbol : Symbol, optional
|
| 268 |
+
The symbol present in expression which gets varied over the given range.
|
| 269 |
+
|
| 270 |
+
Returns
|
| 271 |
+
=======
|
| 272 |
+
|
| 273 |
+
Boolean
|
| 274 |
+
True if ``expression`` is decreasing (either strictly decreasing or
|
| 275 |
+
constant) in the given ``interval``, False otherwise.
|
| 276 |
+
|
| 277 |
+
Examples
|
| 278 |
+
========
|
| 279 |
+
|
| 280 |
+
>>> from sympy import is_decreasing
|
| 281 |
+
>>> from sympy.abc import x, y
|
| 282 |
+
>>> from sympy import S, Interval, oo
|
| 283 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
|
| 284 |
+
True
|
| 285 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
| 286 |
+
True
|
| 287 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 288 |
+
True
|
| 289 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
|
| 290 |
+
False
|
| 291 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
|
| 292 |
+
False
|
| 293 |
+
>>> is_decreasing(-x**2, Interval(-oo, 0))
|
| 294 |
+
False
|
| 295 |
+
>>> is_decreasing(-x**2 + y, Interval(-oo, 0), x)
|
| 296 |
+
False
|
| 297 |
+
|
| 298 |
+
"""
|
| 299 |
+
return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def is_strictly_decreasing(expression, interval=S.Reals, symbol=None):
|
| 303 |
+
"""
|
| 304 |
+
Return whether the function is strictly decreasing in the given interval.
|
| 305 |
+
|
| 306 |
+
Parameters
|
| 307 |
+
==========
|
| 308 |
+
|
| 309 |
+
expression : Expr
|
| 310 |
+
The target function which is being checked.
|
| 311 |
+
interval : Set, optional
|
| 312 |
+
The range of values in which we are testing (defaults to set of
|
| 313 |
+
all real numbers).
|
| 314 |
+
symbol : Symbol, optional
|
| 315 |
+
The symbol present in expression which gets varied over the given range.
|
| 316 |
+
|
| 317 |
+
Returns
|
| 318 |
+
=======
|
| 319 |
+
|
| 320 |
+
Boolean
|
| 321 |
+
True if ``expression`` is strictly decreasing in the given ``interval``,
|
| 322 |
+
False otherwise.
|
| 323 |
+
|
| 324 |
+
Examples
|
| 325 |
+
========
|
| 326 |
+
|
| 327 |
+
>>> from sympy import is_strictly_decreasing
|
| 328 |
+
>>> from sympy.abc import x, y
|
| 329 |
+
>>> from sympy import S, Interval, oo
|
| 330 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 331 |
+
True
|
| 332 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
|
| 333 |
+
False
|
| 334 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
|
| 335 |
+
False
|
| 336 |
+
>>> is_strictly_decreasing(-x**2, Interval(-oo, 0))
|
| 337 |
+
False
|
| 338 |
+
>>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x)
|
| 339 |
+
False
|
| 340 |
+
|
| 341 |
+
"""
|
| 342 |
+
return monotonicity_helper(expression, lambda x: x < 0, interval, symbol)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def is_monotonic(expression, interval=S.Reals, symbol=None):
|
| 346 |
+
"""
|
| 347 |
+
Return whether the function is monotonic in the given interval.
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
==========
|
| 351 |
+
|
| 352 |
+
expression : Expr
|
| 353 |
+
The target function which is being checked.
|
| 354 |
+
interval : Set, optional
|
| 355 |
+
The range of values in which we are testing (defaults to set of
|
| 356 |
+
all real numbers).
|
| 357 |
+
symbol : Symbol, optional
|
| 358 |
+
The symbol present in expression which gets varied over the given range.
|
| 359 |
+
|
| 360 |
+
Returns
|
| 361 |
+
=======
|
| 362 |
+
|
| 363 |
+
Boolean
|
| 364 |
+
True if ``expression`` is monotonic in the given ``interval``,
|
| 365 |
+
False otherwise.
|
| 366 |
+
|
| 367 |
+
Raises
|
| 368 |
+
======
|
| 369 |
+
|
| 370 |
+
NotImplementedError
|
| 371 |
+
Monotonicity check has not been implemented for the queried function.
|
| 372 |
+
|
| 373 |
+
Examples
|
| 374 |
+
========
|
| 375 |
+
|
| 376 |
+
>>> from sympy import is_monotonic
|
| 377 |
+
>>> from sympy.abc import x, y
|
| 378 |
+
>>> from sympy import S, Interval, oo
|
| 379 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
|
| 380 |
+
True
|
| 381 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
| 382 |
+
True
|
| 383 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 384 |
+
True
|
| 385 |
+
>>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
|
| 386 |
+
True
|
| 387 |
+
>>> is_monotonic(-x**2, S.Reals)
|
| 388 |
+
False
|
| 389 |
+
>>> is_monotonic(x**2 + y + 1, Interval(1, 2), x)
|
| 390 |
+
True
|
| 391 |
+
|
| 392 |
+
"""
|
| 393 |
+
from sympy.solvers.solveset import solveset
|
| 394 |
+
|
| 395 |
+
expression = sympify(expression)
|
| 396 |
+
|
| 397 |
+
free = expression.free_symbols
|
| 398 |
+
if symbol is None and len(free) > 1:
|
| 399 |
+
raise NotImplementedError(
|
| 400 |
+
'is_monotonic has not yet been implemented'
|
| 401 |
+
' for all multivariate expressions.'
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
variable = symbol or (free.pop() if free else Symbol('x'))
|
| 405 |
+
turning_points = solveset(expression.diff(variable), variable, interval)
|
| 406 |
+
return interval.intersection(turning_points) is S.EmptySet
|
infer_4_47_1/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d0c6b62b8a2eb4e4f9a149dc8a11cdec992f999a9dfed64ae1396f45fa3635f
|
| 3 |
+
size 152911
|
infer_4_47_1/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2da74a66b5c7d641937b412b1ebd45cda788c95985bca103f6fe094093123a5f
|
| 3 |
+
size 220806
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc
ADDED
|
Binary file (46.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/digits.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
|
| 4 |
+
from sympy.utilities.misc import as_int
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def digits(n, b=10, digits=None):
|
| 8 |
+
"""
|
| 9 |
+
Return a list of the digits of ``n`` in base ``b``. The first
|
| 10 |
+
element in the list is ``b`` (or ``-b`` if ``n`` is negative).
|
| 11 |
+
|
| 12 |
+
Examples
|
| 13 |
+
========
|
| 14 |
+
|
| 15 |
+
>>> from sympy.ntheory.digits import digits
|
| 16 |
+
>>> digits(35)
|
| 17 |
+
[10, 3, 5]
|
| 18 |
+
|
| 19 |
+
If the number is negative, the negative sign will be placed on the
|
| 20 |
+
base (which is the first element in the returned list):
|
| 21 |
+
|
| 22 |
+
>>> digits(-35)
|
| 23 |
+
[-10, 3, 5]
|
| 24 |
+
|
| 25 |
+
Bases other than 10 (and greater than 1) can be selected with ``b``:
|
| 26 |
+
|
| 27 |
+
>>> digits(27, b=2)
|
| 28 |
+
[2, 1, 1, 0, 1, 1]
|
| 29 |
+
|
| 30 |
+
Use the ``digits`` keyword if a certain number of digits is desired:
|
| 31 |
+
|
| 32 |
+
>>> digits(35, digits=4)
|
| 33 |
+
[10, 0, 0, 3, 5]
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
==========
|
| 37 |
+
|
| 38 |
+
n: integer
|
| 39 |
+
The number whose digits are returned.
|
| 40 |
+
|
| 41 |
+
b: integer
|
| 42 |
+
The base in which digits are computed.
|
| 43 |
+
|
| 44 |
+
digits: integer (or None for all digits)
|
| 45 |
+
The number of digits to be returned (padded with zeros, if
|
| 46 |
+
necessary).
|
| 47 |
+
|
| 48 |
+
See Also
|
| 49 |
+
========
|
| 50 |
+
sympy.core.intfunc.num_digits, count_digits
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
b = as_int(b)
|
| 54 |
+
n = as_int(n)
|
| 55 |
+
if b < 2:
|
| 56 |
+
raise ValueError("b must be greater than 1")
|
| 57 |
+
else:
|
| 58 |
+
x, y = abs(n), []
|
| 59 |
+
while x >= b:
|
| 60 |
+
x, r = divmod(x, b)
|
| 61 |
+
y.append(r)
|
| 62 |
+
y.append(x)
|
| 63 |
+
y.append(-b if n < 0 else b)
|
| 64 |
+
y.reverse()
|
| 65 |
+
ndig = len(y) - 1
|
| 66 |
+
if digits is not None:
|
| 67 |
+
if ndig > digits:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"For %s, at least %s digits are needed." % (n, ndig))
|
| 70 |
+
elif ndig < digits:
|
| 71 |
+
y[1:1] = [0]*(digits - ndig)
|
| 72 |
+
return y
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def count_digits(n, b=10):
|
| 76 |
+
"""
|
| 77 |
+
Return a dictionary whose keys are the digits of ``n`` in the
|
| 78 |
+
given base, ``b``, with keys indicating the digits appearing in the
|
| 79 |
+
number and values indicating how many times that digit appeared.
|
| 80 |
+
|
| 81 |
+
Examples
|
| 82 |
+
========
|
| 83 |
+
|
| 84 |
+
>>> from sympy.ntheory import count_digits
|
| 85 |
+
|
| 86 |
+
>>> count_digits(1111339)
|
| 87 |
+
{1: 4, 3: 2, 9: 1}
|
| 88 |
+
|
| 89 |
+
The digits returned are always represented in base-10
|
| 90 |
+
but the number itself can be entered in any format that is
|
| 91 |
+
understood by Python; the base of the number can also be
|
| 92 |
+
given if it is different than 10:
|
| 93 |
+
|
| 94 |
+
>>> n = 0xFA; n
|
| 95 |
+
250
|
| 96 |
+
>>> count_digits(_)
|
| 97 |
+
{0: 1, 2: 1, 5: 1}
|
| 98 |
+
>>> count_digits(n, 16)
|
| 99 |
+
{10: 1, 15: 1}
|
| 100 |
+
|
| 101 |
+
The default dictionary will return a 0 for any digit that did
|
| 102 |
+
not appear in the number. For example, which digits appear 7
|
| 103 |
+
times in ``77!``:
|
| 104 |
+
|
| 105 |
+
>>> from sympy import factorial
|
| 106 |
+
>>> c77 = count_digits(factorial(77))
|
| 107 |
+
>>> [i for i in range(10) if c77[i] == 7]
|
| 108 |
+
[1, 3, 7, 9]
|
| 109 |
+
|
| 110 |
+
See Also
|
| 111 |
+
========
|
| 112 |
+
sympy.core.intfunc.num_digits, digits
|
| 113 |
+
"""
|
| 114 |
+
rv = defaultdict(int, multiset(digits(n, b)).items())
|
| 115 |
+
rv.pop(b) if b in rv else rv.pop(-b) # b or -b is there
|
| 116 |
+
return rv
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def is_palindromic(n, b=10):
|
| 120 |
+
"""return True if ``n`` is the same when read from left to right
|
| 121 |
+
or right to left in the given base, ``b``.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy.ntheory import is_palindromic
|
| 127 |
+
|
| 128 |
+
>>> all(is_palindromic(i) for i in (-11, 1, 22, 121))
|
| 129 |
+
True
|
| 130 |
+
|
| 131 |
+
The second argument allows you to test numbers in other
|
| 132 |
+
bases. For example, 88 is palindromic in base-10 but not
|
| 133 |
+
in base-8:
|
| 134 |
+
|
| 135 |
+
>>> is_palindromic(88, 8)
|
| 136 |
+
False
|
| 137 |
+
|
| 138 |
+
On the other hand, a number can be palindromic in base-8 but
|
| 139 |
+
not in base-10:
|
| 140 |
+
|
| 141 |
+
>>> 0o121, is_palindromic(0o121)
|
| 142 |
+
(81, False)
|
| 143 |
+
|
| 144 |
+
Or it might be palindromic in both bases:
|
| 145 |
+
|
| 146 |
+
>>> oct(121), is_palindromic(121,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import log
|
| 2 |
+
|
| 3 |
+
from sympy.core.random import _randint
|
| 4 |
+
from sympy.external.gmpy import gcd, invert, sqrt
|
| 5 |
+
from sympy.utilities.misc import as_int
|
| 6 |
+
from .generate import sieve, primerange
|
| 7 |
+
from .primetest import isprime
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
#----------------------------------------------------------------------------#
|
| 11 |
+
# #
|
| 12 |
+
# Lenstra's Elliptic Curve Factorization #
|
| 13 |
+
# #
|
| 14 |
+
#----------------------------------------------------------------------------#
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Point:
|
| 18 |
+
"""Montgomery form of Points in an elliptic curve.
|
| 19 |
+
In this form, the addition and doubling of points
|
| 20 |
+
does not need any y-coordinate information thus
|
| 21 |
+
decreasing the number of operations.
|
| 22 |
+
Using Montgomery form we try to perform point addition
|
| 23 |
+
and doubling in least amount of multiplications.
|
| 24 |
+
|
| 25 |
+
The elliptic curve used here is of the form
|
| 26 |
+
(E : b*y**2*z = x**3 + a*x**2*z + x*z**2).
|
| 27 |
+
The a_24 parameter is equal to (a + 2)/4.
|
| 28 |
+
|
| 29 |
+
References
|
| 30 |
+
==========
|
| 31 |
+
|
| 32 |
+
.. [1] Kris Gaj, Soonhak Kwon, Patrick Baier, Paul Kohlbrenner, Hoang Le, Mohammed Khaleeluddin, Ramakrishna Bachimanchi,
|
| 33 |
+
Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware,
|
| 34 |
+
Cryptographic Hardware and Embedded Systems - CHES 2006 (2006), pp. 119-133,
|
| 35 |
+
https://doi.org/10.1007/11894063_10
|
| 36 |
+
https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, x_cord, z_cord, a_24, mod):
|
| 41 |
+
"""
|
| 42 |
+
Initial parameters for the Point class.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
==========
|
| 46 |
+
|
| 47 |
+
x_cord : X coordinate of the Point
|
| 48 |
+
z_cord : Z coordinate of the Point
|
| 49 |
+
a_24 : Parameter of the elliptic curve in Montgomery form
|
| 50 |
+
mod : modulus
|
| 51 |
+
"""
|
| 52 |
+
self.x_cord = x_cord
|
| 53 |
+
self.z_cord = z_cord
|
| 54 |
+
self.a_24 = a_24
|
| 55 |
+
self.mod = mod
|
| 56 |
+
|
| 57 |
+
def __eq__(self, other):
|
| 58 |
+
"""Two points are equal if X/Z of both points are equal
|
| 59 |
+
"""
|
| 60 |
+
if self.a_24 != other.a_24 or self.mod != other.mod:
|
| 61 |
+
return False
|
| 62 |
+
return self.x_cord * other.z_cord % self.mod ==\
|
| 63 |
+
other.x_cord * self.z_cord % self.mod
|
| 64 |
+
|
| 65 |
+
def add(self, Q, diff):
|
| 66 |
+
"""
|
| 67 |
+
Add two points self and Q where diff = self - Q. Moreover the assumption
|
| 68 |
+
is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm
|
| 69 |
+
requires 6 multiplications. Here the difference between the points
|
| 70 |
+
is already known and using this algorithm speeds up the addition
|
| 71 |
+
by reducing the number of multiplication required. Also in the
|
| 72 |
+
mont_ladder algorithm is constructed in a way so that the difference
|
| 73 |
+
between intermediate points is always equal to the initial point.
|
| 74 |
+
So, we always know what the difference between the point is.
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
Parameters
|
| 78 |
+
==========
|
| 79 |
+
|
| 80 |
+
Q : point on the curve in Montgomery form
|
| 81 |
+
diff : self - Q
|
| 82 |
+
|
| 83 |
+
Examples
|
| 84 |
+
========
|
| 85 |
+
|
| 86 |
+
>>> from sympy.ntheory.ecm import Point
|
| 87 |
+
>>> p1 = Point(11, 16, 7, 29)
|
| 88 |
+
>>> p2 = Point(13, 10, 7, 29)
|
| 89 |
+
>>> p3 = p2.add(p1, p1)
|
| 90 |
+
>>> p3.x_cord
|
| 91 |
+
23
|
| 92 |
+
>>> p3.z_cord
|
| 93 |
+
17
|
| 94 |
+
"""
|
| 95 |
+
u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord)
|
| 96 |
+
v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord)
|
| 97 |
+
add, subt = u + v, u - v
|
| 98 |
+
x_cord = diff.z_cord * add * add % self.mod
|
| 99 |
+
z_cord = diff.x_cord * subt * subt % self.mod
|
| 100 |
+
return Point(x_cord, z_cord, self.a_24, self.mod)
|
| 101 |
+
|
| 102 |
+
def double(self):
|
| 103 |
+
"""
|
| 104 |
+
Doubles a point in an elliptic curve in Montgomery form.
|
| 105 |
+
This algorithm requires 5 multiplications.
|
| 106 |
+
|
| 107 |
+
Examples
|
| 108 |
+
========
|
| 109 |
+
|
| 110 |
+
>>> from sympy.ntheory.ecm import Point
|
| 111 |
+
>>> p1 = Point(11, 16, 7, 29)
|
| 112 |
+
>>> p2 = p1.double()
|
| 113 |
+
>>> p2.x_cord
|
| 114 |
+
13
|
| 115 |
+
>>> p2.z_cord
|
| 116 |
+
10
|
| 117 |
+
"""
|
| 118 |
+
u = pow(self.x_cord + self.z_cord, 2, self.mod)
|
| 119 |
+
v = pow(self.x_cord - self.z_cord, 2, self.mod)
|
| 120 |
+
diff = u - v
|
| 121 |
+
x_cord = u*v % self.mod
|
| 122 |
+
z_cord = diff*(v + self.a_24*diff) % self.mod
|
| 123 |
+
return Point(x_cord, z_cord, self.a_24, self.mod)
|
| 124 |
+
|
| 125 |
+
def mont_ladder(self, k):
|
| 126 |
+
"""
|
| 127 |
+
Scalar multiplication of a point in Montgomery form
|
| 128 |
+
using Montgomery Ladder Algorithm.
|
| 129 |
+
A total of 11 multiplications are required in each step of this
|
| 130 |
+
algorithm.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
==========
|
| 134 |
+
|
| 135 |
+
k : The positive integer multiplier
|
| 136 |
+
|
| 137 |
+
Examples
|
| 138 |
+
========
|
| 139 |
+
|
| 140 |
+
>>> from sympy.ntheory.ecm import Point
|
| 141 |
+
>>> p1 = Point(11, 16, 7, 29)
|
| 142 |
+
>>> p3 = p1.mont_ladder(3)
|
| 143 |
+
>>> p3.x_cord
|
| 144 |
+
23
|
| 145 |
+
>>> p3.z_cord
|
| 146 |
+
17
|
| 147 |
+
"""
|
| 148 |
+
Q = self
|
| 149 |
+
R = self.double()
|
| 150 |
+
for i in bin(k)[3:]:
|
| 151 |
+
if i == '1':
|
| 152 |
+
Q = R.add(Q, self)
|
| 153 |
+
R = R.double()
|
| 154 |
+
else:
|
| 155 |
+
R = Q.add(R, self)
|
| 156 |
+
Q = Q.double()
|
| 157 |
+
return Q
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200, seed=None):
|
| 161 |
+
"""Returns one factor of n using
|
| 162 |
+
Lenstra's 2 Stage Elliptic curve Factorization
|
| 163 |
+
with Suyama's Parameterization. Here Montgomery
|
| 164 |
+
arithmetic is used for fast computation of addition
|
| 165 |
+
and doubling of points in elliptic curve.
|
| 166 |
+
|
| 167 |
+
Explanation
|
| 168 |
+
===========
|
| 169 |
+
|
| 170 |
+
This ECM method considers elliptic curves in Montgomery
|
| 171 |
+
form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves
|
| 172 |
+
elliptic curve operations (mod N), where the elements in
|
| 173 |
+
Z are reduced (mod N). Since N is not a prime, E over FF(N)
|
| 174 |
+
is not really an elliptic curve but we can still do point additions
|
| 175 |
+
and doubling as if FF(N) was a field.
|
| 176 |
+
|
| 177 |
+
Stage 1 : The basic algorithm involves taking a random point (P) on an
|
| 178 |
+
elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm.
|
| 179 |
+
Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|,
|
| 180 |
+
might be a smooth number that divides k. Then we have k = l * |E(FF(q))|
|
| 181 |
+
for some l. For any point belonging to the curve E, |E(FF(q))|*P = O,
|
| 182 |
+
hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn
|
| 183 |
+
factor of N (q) can be recovered by taking gcd(kP.z_cord, N).
|
| 184 |
+
|
| 185 |
+
Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize
|
| 186 |
+
the fact that even if kP != 0, the value of k might miss just one large
|
| 187 |
+
prime divisor of |E(FF(q))|. In this case we only need to compute the
|
| 188 |
+
scalar multiplication by p to get p*k*P = O. Here a second bound B2
|
| 189 |
+
restrict the size of possible values of p.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
==========
|
| 193 |
+
|
| 194 |
+
n : Number to be Factored
|
| 195 |
+
B1 : Stage 1 Bound. Must be an even number.
|
| 196 |
+
B2 : Stage 2 Bound. Must be an even number.
|
| 197 |
+
max_curve : Maximum number of curves generated
|
| 198 |
+
|
| 199 |
+
Returns
|
| 200 |
+
=======
|
| 201 |
+
|
| 202 |
+
integer | None : ``n`` (if it is prime) else a non-trivial divisor of ``n``. ``None`` if not found
|
| 203 |
+
|
| 204 |
+
References
|
| 205 |
+
==========
|
| 206 |
+
|
| 207 |
+
.. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
|
| 208 |
+
2nd Edition (2005), page 344, ISBN:978-0387252827
|
| 209 |
+
"""
|
| 210 |
+
randint = _randint(seed)
|
| 211 |
+
if isprime(n):
|
| 212 |
+
return n
|
| 213 |
+
|
| 214 |
+
# When calculating T, if (B1 - 2*D) is negative, it cannot be calculated.
|
| 215 |
+
D = min(sqrt(B2), B1 // 2 - 1)
|
| 216 |
+
sieve.extend(D)
|
| 217 |
+
beta = [0] * D
|
| 218 |
+
S = [0] * D
|
| 219 |
+
k = 1
|
| 220 |
+
for p in primerange(2, B1 + 1):
|
| 221 |
+
k *= pow(p, int(log(B1, p)))
|
| 222 |
+
|
| 223 |
+
# Pre-calculate the prime numbers to be used in stage 2.
|
| 224 |
+
# Using the fact that the x-coordinates of point P and its
|
| 225 |
+
# inverse -P coincide, the number of primes to be checked
|
| 226 |
+
# in stage 2 can be reduced.
|
| 227 |
+
deltas_list = []
|
| 228 |
+
for r in range(B1 + 2*D, B2 + 2*D, 4*D):
|
| 229 |
+
deltas = set()
|
| 230 |
+
deltas.update((abs(q - r) - 1) // 2 for q in primerange(r - 2*D, r + 2*D))
|
| 231 |
+
# d in deltas iff r+(2d+1) and/or r-(2d+1) is prime
|
| 232 |
+
deltas_list.append(list(deltas))
|
| 233 |
+
|
| 234 |
+
for _ in range(max_curve):
|
| 235 |
+
#Suyama's Parametrization
|
| 236 |
+
sigma = randint(6, n - 1)
|
| 237 |
+
u = (sigma**2 - 5) % n
|
| 238 |
+
v = (4*sigma) % n
|
| 239 |
+
u_3 = pow(u, 3, n)
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
# We use the elliptic curve y**2 = x**3 + a*x**2 + x
|
| 243 |
+
# where a = pow(v - u, 3, n)*(3*u + v)*invert(4*u_3*v, n) - 2
|
| 244 |
+
# However, we do not declare a because it is more convenient
|
| 245 |
+
# to use a24 = (a + 2)*invert(4, n) in the calculation.
|
| 246 |
+
a24 = pow(v - u, 3, n)*(3*u + v)*invert(16*u_3*v, n) % n
|
| 247 |
+
except ZeroDivisionError:
|
| 248 |
+
#If the invert(16*u_3*v, n) doesn't exist (i.e., g != 1)
|
| 249 |
+
g = gcd(2*u_3*v, n)
|
| 250 |
+
#If g = n, try another curve
|
| 251 |
+
if g == n:
|
| 252 |
+
continue
|
| 253 |
+
return g
|
| 254 |
+
|
| 255 |
+
Q = Point(u_3, pow(v, 3, n), a24, n)
|
| 256 |
+
Q = Q.mont_ladder(k)
|
| 257 |
+
g = gcd(Q.z_cord, n)
|
| 258 |
+
|
| 259 |
+
#Stage 1 factor
|
| 260 |
+
if g != 1 and g != n:
|
| 261 |
+
return g
|
| 262 |
+
#Stage 1 failure. Q.z = 0, Try another curve
|
| 263 |
+
elif g == n:
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
#Stage 2 - Improved Standard Continuation
|
| 267 |
+
S[0] = Q
|
| 268 |
+
Q2 = Q.double()
|
| 269 |
+
S[1] = Q2.add(Q, Q)
|
| 270 |
+
beta[0] = (S[0].x_cord*S[0].z_cord) % n
|
| 271 |
+
beta[1] = (S[1].x_cord*S[1].z_cord) % n
|
| 272 |
+
for d in range(2, D):
|
| 273 |
+
S[d] = S[d - 1].add(Q2, S[d - 2])
|
| 274 |
+
beta[d] = (S[d].x_cord*S[d].z_cord) % n
|
| 275 |
+
# i.e., S[i] = Q.mont_ladder(2*i + 1)
|
| 276 |
+
|
| 277 |
+
g = 1
|
| 278 |
+
W = Q.mont_ladder(4*D)
|
| 279 |
+
T = Q.mont_ladder(B1 - 2*D)
|
| 280 |
+
R = Q.mont_ladder(B1 + 2*D)
|
| 281 |
+
for deltas in deltas_list:
|
| 282 |
+
# R = Q.mont_ladder(r) where r in range(B1 + 2*D, B2 + 2*D, 4*D)
|
| 283 |
+
alpha = (R.x_cord*R.z_cord) % n
|
| 284 |
+
for delta in deltas:
|
| 285 |
+
# We want to calculate
|
| 286 |
+
# f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord
|
| 287 |
+
f = (R.x_cord - S[delta].x_cord)*\
|
| 288 |
+
(R.z_cord + S[delta].z_cord) - alpha + beta[delta]
|
| 289 |
+
g = (g*f) % n
|
| 290 |
+
T, R = R, R.add(W, T)
|
| 291 |
+
g = gcd(n, g)
|
| 292 |
+
|
| 293 |
+
#Stage 2 Factor found
|
| 294 |
+
if g != 1 and g != n:
|
| 295 |
+
return g
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234):
|
| 299 |
+
"""Performs factorization using Lenstra's Elliptic curve method.
|
| 300 |
+
|
| 301 |
+
This function repeatedly calls ``_ecm_one_factor`` to compute the factors
|
| 302 |
+
of n. First all the small factors are taken out using trial division.
|
| 303 |
+
Then ``_ecm_one_factor`` is used to compute one factor at a time.
|
| 304 |
+
|
| 305 |
+
Parameters
|
| 306 |
+
==========
|
| 307 |
+
|
| 308 |
+
n : Number to be Factored
|
| 309 |
+
B1 : Stage 1 Bound. Must be an even number.
|
| 310 |
+
B2 : Stage 2 Bound. Must be an even number.
|
| 311 |
+
max_curve : Maximum number of curves generated
|
| 312 |
+
seed : Initialize pseudorandom generator
|
| 313 |
+
|
| 314 |
+
Examples
|
| 315 |
+
========
|
| 316 |
+
|
| 317 |
+
>>> from sympy.ntheory import ecm
|
| 318 |
+
>>> ecm(25645121643901801)
|
| 319 |
+
{5394769, 4753701529}
|
| 320 |
+
>>> ecm(9804659461513846513)
|
| 321 |
+
{4641991, 2112166839943}
|
| 322 |
+
"""
|
| 323 |
+
n = as_int(n)
|
| 324 |
+
if B1 % 2 != 0 or B2 % 2 != 0:
|
| 325 |
+
raise ValueError("both bounds must be even")
|
| 326 |
+
_factors = set()
|
| 327 |
+
for prime in sieve.primerange(1, 100000):
|
| 328 |
+
if n % prime == 0:
|
| 329 |
+
_factors.add(prime)
|
| 330 |
+
while(n % prime == 0):
|
| 331 |
+
n //= prime
|
| 332 |
+
while(n > 1):
|
| 333 |
+
factor = _ecm_one_factor(n, B1, B2, max_curve, seed)
|
| 334 |
+
if factor is None:
|
| 335 |
+
raise ValueError("Increase the bounds")
|
| 336 |
+
_factors.add(factor)
|
| 337 |
+
n //= factor
|
| 338 |
+
|
| 339 |
+
factors = set()
|
| 340 |
+
for factor in _factors:
|
| 341 |
+
if isprime(factor):
|
| 342 |
+
factors.add(factor)
|
| 343 |
+
continue
|
| 344 |
+
factors |= ecm(factor)
|
| 345 |
+
return factors
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/generate.py
ADDED
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generating and counting primes.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from bisect import bisect, bisect_left
|
| 7 |
+
from itertools import count
|
| 8 |
+
# Using arrays for sieving instead of lists greatly reduces
|
| 9 |
+
# memory consumption
|
| 10 |
+
from array import array as _array
|
| 11 |
+
|
| 12 |
+
from sympy.core.random import randint
|
| 13 |
+
from sympy.external.gmpy import sqrt
|
| 14 |
+
from .primetest import isprime
|
| 15 |
+
from sympy.utilities.decorator import deprecated
|
| 16 |
+
from sympy.utilities.misc import as_int
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _as_int_ceiling(a):
|
| 20 |
+
""" Wrapping ceiling in as_int will raise an error if there was a problem
|
| 21 |
+
determining whether the expression was exactly an integer or not."""
|
| 22 |
+
from sympy.functions.elementary.integers import ceiling
|
| 23 |
+
return as_int(ceiling(a))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Sieve:
|
| 27 |
+
"""A list of prime numbers, implemented as a dynamically
|
| 28 |
+
growing sieve of Eratosthenes. When a lookup is requested involving
|
| 29 |
+
an odd number that has not been sieved, the sieve is automatically
|
| 30 |
+
extended up to that number. Implementation details limit the number of
|
| 31 |
+
primes to ``2^32-1``.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
========
|
| 35 |
+
|
| 36 |
+
>>> from sympy import sieve
|
| 37 |
+
>>> sieve._reset() # this line for doctest only
|
| 38 |
+
>>> 25 in sieve
|
| 39 |
+
False
|
| 40 |
+
>>> sieve._list
|
| 41 |
+
array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
# data shared (and updated) by all Sieve instances
|
| 45 |
+
def __init__(self, sieve_interval=1_000_000):
|
| 46 |
+
""" Initial parameters for the Sieve class.
|
| 47 |
+
|
| 48 |
+
Parameters
|
| 49 |
+
==========
|
| 50 |
+
|
| 51 |
+
sieve_interval (int): Amount of memory to be used
|
| 52 |
+
|
| 53 |
+
Raises
|
| 54 |
+
======
|
| 55 |
+
|
| 56 |
+
ValueError
|
| 57 |
+
If ``sieve_interval`` is not positive.
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
self._n = 6
|
| 61 |
+
self._list = _array('L', [2, 3, 5, 7, 11, 13]) # primes
|
| 62 |
+
self._tlist = _array('L', [0, 1, 1, 2, 2, 4]) # totient
|
| 63 |
+
self._mlist = _array('i', [0, 1, -1, -1, 0, -1]) # mobius
|
| 64 |
+
if sieve_interval <= 0:
|
| 65 |
+
raise ValueError("sieve_interval should be a positive integer")
|
| 66 |
+
self.sieve_interval = sieve_interval
|
| 67 |
+
assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
|
| 68 |
+
|
| 69 |
+
def __repr__(self):
|
| 70 |
+
return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
|
| 71 |
+
"%s sieve (%i): %i, %i, %i, ... %i, %i\n"
|
| 72 |
+
"%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
|
| 73 |
+
'prime', len(self._list),
|
| 74 |
+
self._list[0], self._list[1], self._list[2],
|
| 75 |
+
self._list[-2], self._list[-1],
|
| 76 |
+
'totient', len(self._tlist),
|
| 77 |
+
self._tlist[0], self._tlist[1],
|
| 78 |
+
self._tlist[2], self._tlist[-2], self._tlist[-1],
|
| 79 |
+
'mobius', len(self._mlist),
|
| 80 |
+
self._mlist[0], self._mlist[1],
|
| 81 |
+
self._mlist[2], self._mlist[-2], self._mlist[-1])
|
| 82 |
+
|
| 83 |
+
def _reset(self, prime=None, totient=None, mobius=None):
|
| 84 |
+
"""Reset all caches (default). To reset one or more set the
|
| 85 |
+
desired keyword to True."""
|
| 86 |
+
if all(i is None for i in (prime, totient, mobius)):
|
| 87 |
+
prime = totient = mobius = True
|
| 88 |
+
if prime:
|
| 89 |
+
self._list = self._list[:self._n]
|
| 90 |
+
if totient:
|
| 91 |
+
self._tlist = self._tlist[:self._n]
|
| 92 |
+
if mobius:
|
| 93 |
+
self._mlist = self._mlist[:self._n]
|
| 94 |
+
|
| 95 |
+
def extend(self, n):
|
| 96 |
+
"""Grow the sieve to cover all primes <= n.
|
| 97 |
+
|
| 98 |
+
Examples
|
| 99 |
+
========
|
| 100 |
+
|
| 101 |
+
>>> from sympy import sieve
|
| 102 |
+
>>> sieve._reset() # this line for doctest only
|
| 103 |
+
>>> sieve.extend(30)
|
| 104 |
+
>>> sieve[10] == 29
|
| 105 |
+
True
|
| 106 |
+
"""
|
| 107 |
+
n = int(n)
|
| 108 |
+
# `num` is even at any point in the function.
|
| 109 |
+
# This satisfies the condition required by `self._primerange`.
|
| 110 |
+
num = self._list[-1] + 1
|
| 111 |
+
if n < num:
|
| 112 |
+
return
|
| 113 |
+
num2 = num**2
|
| 114 |
+
while num2 <= n:
|
| 115 |
+
self._list += _array('L', self._primerange(num, num2))
|
| 116 |
+
num, num2 = num2, num2**2
|
| 117 |
+
# Merge the sieves
|
| 118 |
+
self._list += _array('L', self._primerange(num, n + 1))
|
| 119 |
+
|
| 120 |
+
def _primerange(self, a, b):
|
| 121 |
+
""" Generate all prime numbers in the range (a, b).
|
| 122 |
+
|
| 123 |
+
Parameters
|
| 124 |
+
==========
|
| 125 |
+
|
| 126 |
+
a, b : positive integers assuming the following conditions
|
| 127 |
+
* a is an even number
|
| 128 |
+
* 2 < self._list[-1] < a < b < nextprime(self._list[-1])**2
|
| 129 |
+
|
| 130 |
+
Yields
|
| 131 |
+
======
|
| 132 |
+
|
| 133 |
+
p (int): prime numbers such that ``a < p < b``
|
| 134 |
+
|
| 135 |
+
Examples
|
| 136 |
+
========
|
| 137 |
+
|
| 138 |
+
>>> from sympy.ntheory.generate import Sieve
|
| 139 |
+
>>> s = Sieve()
|
| 140 |
+
>>> s._list[-1]
|
| 141 |
+
13
|
| 142 |
+
>>> list(s._primerange(18, 31))
|
| 143 |
+
[19, 23, 29]
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
if b % 2:
|
| 147 |
+
b -= 1
|
| 148 |
+
while a < b:
|
| 149 |
+
block_size = min(self.sieve_interval, (b - a) // 2)
|
| 150 |
+
# Create the list such that block[x] iff (a + 2x + 1) is prime.
|
| 151 |
+
# Note that even numbers are not considered here.
|
| 152 |
+
block = [True] * block_size
|
| 153 |
+
for p in self._list[1:bisect(self._list, sqrt(a + 2 * block_size + 1))]:
|
| 154 |
+
for t in range((-(a + 1 + p) // 2) % p, block_size, p):
|
| 155 |
+
block[t] = False
|
| 156 |
+
for idx, p in enumerate(block):
|
| 157 |
+
if p:
|
| 158 |
+
yield a + 2 * idx + 1
|
| 159 |
+
a += 2 * block_size
|
| 160 |
+
|
| 161 |
+
def extend_to_no(self, i):
|
| 162 |
+
"""Extend to include the ith prime number.
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
==========
|
| 166 |
+
|
| 167 |
+
i : integer
|
| 168 |
+
|
| 169 |
+
Examples
|
| 170 |
+
========
|
| 171 |
+
|
| 172 |
+
>>> from sympy import sieve
|
| 173 |
+
>>> sieve._reset() # this line for doctest only
|
| 174 |
+
>>> sieve.extend_to_no(9)
|
| 175 |
+
>>> sieve._list
|
| 176 |
+
array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
|
| 177 |
+
|
| 178 |
+
Notes
|
| 179 |
+
=====
|
| 180 |
+
|
| 181 |
+
The list is extended by 50% if it is too short, so it is
|
| 182 |
+
likely that it will be longer than requested.
|
| 183 |
+
"""
|
| 184 |
+
i = as_int(i)
|
| 185 |
+
while len(self._list) < i:
|
| 186 |
+
self.extend(int(self._list[-1] * 1.5))
|
| 187 |
+
|
| 188 |
+
def primerange(self, a, b=None):
|
| 189 |
+
"""Generate all prime numbers in the range [2, a) or [a, b).
|
| 190 |
+
|
| 191 |
+
Examples
|
| 192 |
+
========
|
| 193 |
+
|
| 194 |
+
>>> from sympy import sieve, prime
|
| 195 |
+
|
| 196 |
+
All primes less than 19:
|
| 197 |
+
|
| 198 |
+
>>> print([i for i in sieve.primerange(19)])
|
| 199 |
+
[2, 3, 5, 7, 11, 13, 17]
|
| 200 |
+
|
| 201 |
+
All primes greater than or equal to 7 and less than 19:
|
| 202 |
+
|
| 203 |
+
>>> print([i for i in sieve.primerange(7, 19)])
|
| 204 |
+
[7, 11, 13, 17]
|
| 205 |
+
|
| 206 |
+
All primes through the 10th prime
|
| 207 |
+
|
| 208 |
+
>>> list(sieve.primerange(prime(10) + 1))
|
| 209 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
| 210 |
+
|
| 211 |
+
"""
|
| 212 |
+
if b is None:
|
| 213 |
+
b = _as_int_ceiling(a)
|
| 214 |
+
a = 2
|
| 215 |
+
else:
|
| 216 |
+
a = max(2, _as_int_ceiling(a))
|
| 217 |
+
b = _as_int_ceiling(b)
|
| 218 |
+
if a >= b:
|
| 219 |
+
return
|
| 220 |
+
self.extend(b)
|
| 221 |
+
yield from self._list[bisect_left(self._list, a):
|
| 222 |
+
bisect_left(self._list, b)]
|
| 223 |
+
|
| 224 |
+
def totientrange(self, a, b):
|
| 225 |
+
"""Generate all totient numbers for the range [a, b).
|
| 226 |
+
|
| 227 |
+
Examples
|
| 228 |
+
========
|
| 229 |
+
|
| 230 |
+
>>> from sympy import sieve
|
| 231 |
+
>>> print([i for i in sieve.totientrange(7, 18)])
|
| 232 |
+
[6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
|
| 233 |
+
"""
|
| 234 |
+
a = max(1, _as_int_ceiling(a))
|
| 235 |
+
b = _as_int_ceiling(b)
|
| 236 |
+
n = len(self._tlist)
|
| 237 |
+
if a >= b:
|
| 238 |
+
return
|
| 239 |
+
elif b <= n:
|
| 240 |
+
for i in range(a, b):
|
| 241 |
+
yield self._tlist[i]
|
| 242 |
+
else:
|
| 243 |
+
self._tlist += _array('L', range(n, b))
|
| 244 |
+
for i in range(1, n):
|
| 245 |
+
ti = self._tlist[i]
|
| 246 |
+
if ti == i - 1:
|
| 247 |
+
startindex = (n + i - 1) // i * i
|
| 248 |
+
for j in range(startindex, b, i):
|
| 249 |
+
self._tlist[j] -= self._tlist[j] // i
|
| 250 |
+
if i >= a:
|
| 251 |
+
yield ti
|
| 252 |
+
|
| 253 |
+
for i in range(n, b):
|
| 254 |
+
ti = self._tlist[i]
|
| 255 |
+
if ti == i:
|
| 256 |
+
for j in range(i, b, i):
|
| 257 |
+
self._tlist[j] -= self._tlist[j] // i
|
| 258 |
+
if i >= a:
|
| 259 |
+
yield self._tlist[i]
|
| 260 |
+
|
| 261 |
+
def mobiusrange(self, a, b):
|
| 262 |
+
"""Generate all mobius numbers for the range [a, b).
|
| 263 |
+
|
| 264 |
+
Parameters
|
| 265 |
+
==========
|
| 266 |
+
|
| 267 |
+
a : integer
|
| 268 |
+
First number in range
|
| 269 |
+
|
| 270 |
+
b : integer
|
| 271 |
+
First number outside of range
|
| 272 |
+
|
| 273 |
+
Examples
|
| 274 |
+
========
|
| 275 |
+
|
| 276 |
+
>>> from sympy import sieve
|
| 277 |
+
>>> print([i for i in sieve.mobiusrange(7, 18)])
|
| 278 |
+
[-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
|
| 279 |
+
"""
|
| 280 |
+
a = max(1, _as_int_ceiling(a))
|
| 281 |
+
b = _as_int_ceiling(b)
|
| 282 |
+
n = len(self._mlist)
|
| 283 |
+
if a >= b:
|
| 284 |
+
return
|
| 285 |
+
elif b <= n:
|
| 286 |
+
for i in range(a, b):
|
| 287 |
+
yield self._mlist[i]
|
| 288 |
+
else:
|
| 289 |
+
self._mlist += _array('i', [0]*(b - n))
|
| 290 |
+
for i in range(1, n):
|
| 291 |
+
mi = self._mlist[i]
|
| 292 |
+
startindex = (n + i - 1) // i * i
|
| 293 |
+
for j in range(startindex, b, i):
|
| 294 |
+
self._mlist[j] -= mi
|
| 295 |
+
if i >= a:
|
| 296 |
+
yield mi
|
| 297 |
+
|
| 298 |
+
for i in range(n, b):
|
| 299 |
+
mi = self._mlist[i]
|
| 300 |
+
for j in range(2 * i, b, i):
|
| 301 |
+
self._mlist[j] -= mi
|
| 302 |
+
if i >= a:
|
| 303 |
+
yield mi
|
| 304 |
+
|
| 305 |
+
def search(self, n):
|
| 306 |
+
"""Return the indices i, j of the primes that bound n.
|
| 307 |
+
|
| 308 |
+
If n is prime then i == j.
|
| 309 |
+
|
| 310 |
+
Although n can be an expression, if ceiling cannot convert
|
| 311 |
+
it to an integer then an n error will be raised.
|
| 312 |
+
|
| 313 |
+
Examples
|
| 314 |
+
========
|
| 315 |
+
|
| 316 |
+
>>> from sympy import sieve
|
| 317 |
+
>>> sieve.search(25)
|
| 318 |
+
(9, 10)
|
| 319 |
+
>>> sieve.search(23)
|
| 320 |
+
(9, 9)
|
| 321 |
+
"""
|
| 322 |
+
test = _as_int_ceiling(n)
|
| 323 |
+
n = as_int(n)
|
| 324 |
+
if n < 2:
|
| 325 |
+
raise ValueError("n should be >= 2 but got: %s" % n)
|
| 326 |
+
if n > self._list[-1]:
|
| 327 |
+
self.extend(n)
|
| 328 |
+
b = bisect(self._list, n)
|
| 329 |
+
if self._list[b - 1] == test:
|
| 330 |
+
return b, b
|
| 331 |
+
else:
|
| 332 |
+
return b, b + 1
|
| 333 |
+
|
| 334 |
+
def __contains__(self, n):
|
| 335 |
+
try:
|
| 336 |
+
n = as_int(n)
|
| 337 |
+
assert n >= 2
|
| 338 |
+
except (ValueError, AssertionError):
|
| 339 |
+
return False
|
| 340 |
+
if n % 2 == 0:
|
| 341 |
+
return n == 2
|
| 342 |
+
a, b = self.search(n)
|
| 343 |
+
return a == b
|
| 344 |
+
|
| 345 |
+
def __iter__(self):
|
| 346 |
+
for n in count(1):
|
| 347 |
+
yield self[n]
|
| 348 |
+
|
| 349 |
+
def __getitem__(self, n):
|
| 350 |
+
"""Return the nth prime number"""
|
| 351 |
+
if isinstance(n, slice):
|
| 352 |
+
self.extend_to_no(n.stop)
|
| 353 |
+
# Python 2.7 slices have 0 instead of None for start, so
|
| 354 |
+
# we can't default to 1.
|
| 355 |
+
start = n.start if n.start is not None else 0
|
| 356 |
+
if start < 1:
|
| 357 |
+
# sieve[:5] would be empty (starting at -1), let's
|
| 358 |
+
# just be explicit and raise.
|
| 359 |
+
raise IndexError("Sieve indices start at 1.")
|
| 360 |
+
return self._list[start - 1:n.stop - 1:n.step]
|
| 361 |
+
else:
|
| 362 |
+
if n < 1:
|
| 363 |
+
# offset is one, so forbid explicit access to sieve[0]
|
| 364 |
+
# (would surprisingly return the last one).
|
| 365 |
+
raise IndexError("Sieve indices start at 1.")
|
| 366 |
+
n = as_int(n)
|
| 367 |
+
self.extend_to_no(n)
|
| 368 |
+
return self._list[n - 1]
|
| 369 |
+
|
| 370 |
+
# Generate a global object for repeated use in trial division etc
|
| 371 |
+
sieve = Sieve()
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def prime(nth):
|
| 375 |
+
r""" Return the nth prime, with the primes indexed as prime(1) = 2,
|
| 376 |
+
prime(2) = 3, etc.... The nth prime is approximately $n\log(n)$.
|
| 377 |
+
|
| 378 |
+
Logarithmic integral of $x$ is a pretty nice approximation for number of
|
| 379 |
+
primes $\le x$, i.e.
|
| 380 |
+
li(x) ~ pi(x)
|
| 381 |
+
In fact, for the numbers we are concerned about( x<1e11 ),
|
| 382 |
+
li(x) - pi(x) < 50000
|
| 383 |
+
|
| 384 |
+
Also,
|
| 385 |
+
li(x) > pi(x) can be safely assumed for the numbers which
|
| 386 |
+
can be evaluated by this function.
|
| 387 |
+
|
| 388 |
+
Here, we find the least integer m such that li(m) > n using binary search.
|
| 389 |
+
Now pi(m-1) < li(m-1) <= n,
|
| 390 |
+
|
| 391 |
+
We find pi(m - 1) using primepi function.
|
| 392 |
+
|
| 393 |
+
Starting from m, we have to find n - pi(m-1) more primes.
|
| 394 |
+
|
| 395 |
+
For the inputs this implementation can handle, we will have to test
|
| 396 |
+
primality for at max about 10**5 numbers, to get our answer.
|
| 397 |
+
|
| 398 |
+
Examples
|
| 399 |
+
========
|
| 400 |
+
|
| 401 |
+
>>> from sympy import prime
|
| 402 |
+
>>> prime(10)
|
| 403 |
+
29
|
| 404 |
+
>>> prime(1)
|
| 405 |
+
2
|
| 406 |
+
>>> prime(100000)
|
| 407 |
+
1299709
|
| 408 |
+
|
| 409 |
+
See Also
|
| 410 |
+
========
|
| 411 |
+
|
| 412 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
| 413 |
+
primerange : Generate all primes in a given range
|
| 414 |
+
primepi : Return the number of primes less than or equal to n
|
| 415 |
+
|
| 416 |
+
References
|
| 417 |
+
==========
|
| 418 |
+
|
| 419 |
+
.. [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
|
| 420 |
+
.. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
|
| 421 |
+
.. [3] https://en.wikipedia.org/wiki/Skewes%27_number
|
| 422 |
+
"""
|
| 423 |
+
n = as_int(nth)
|
| 424 |
+
if n < 1:
|
| 425 |
+
raise ValueError("nth must be a positive integer; prime(1) == 2")
|
| 426 |
+
if n <= len(sieve._list):
|
| 427 |
+
return sieve[n]
|
| 428 |
+
|
| 429 |
+
from sympy.functions.elementary.exponential import log
|
| 430 |
+
from sympy.functions.special.error_functions import li
|
| 431 |
+
a = 2 # Lower bound for binary search
|
| 432 |
+
# leave n inside int since int(i*r) != i*int(r) is not a valid property
|
| 433 |
+
# e.g. int(2*.5) != 2*int(.5)
|
| 434 |
+
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
|
| 435 |
+
|
| 436 |
+
while a < b:
|
| 437 |
+
mid = (a + b) >> 1
|
| 438 |
+
if li(mid) > n:
|
| 439 |
+
b = mid
|
| 440 |
+
else:
|
| 441 |
+
a = mid + 1
|
| 442 |
+
n_primes = _primepi(a - 1)
|
| 443 |
+
while n_primes < n:
|
| 444 |
+
if isprime(a):
|
| 445 |
+
n_primes += 1
|
| 446 |
+
a += 1
|
| 447 |
+
return a - 1
|
| 448 |
+
|
| 449 |
+
@deprecated("""\
|
| 450 |
+
The `sympy.ntheory.generate.primepi` has been moved to `sympy.functions.combinatorial.numbers.primepi`.""",
|
| 451 |
+
deprecated_since_version="1.13",
|
| 452 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 453 |
+
def primepi(n):
|
| 454 |
+
r""" Represents the prime counting function pi(n) = the number
|
| 455 |
+
of prime numbers less than or equal to n.
|
| 456 |
+
|
| 457 |
+
.. deprecated:: 1.13
|
| 458 |
+
|
| 459 |
+
The ``primepi`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primepi`
|
| 460 |
+
instead. See its documentation for more information. See
|
| 461 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 462 |
+
|
| 463 |
+
Algorithm Description:
|
| 464 |
+
|
| 465 |
+
In sieve method, we remove all multiples of prime p
|
| 466 |
+
except p itself.
|
| 467 |
+
|
| 468 |
+
Let phi(i,j) be the number of integers 2 <= k <= i
|
| 469 |
+
which remain after sieving from primes less than
|
| 470 |
+
or equal to j.
|
| 471 |
+
Clearly, pi(n) = phi(n, sqrt(n))
|
| 472 |
+
|
| 473 |
+
If j is not a prime,
|
| 474 |
+
phi(i,j) = phi(i, j - 1)
|
| 475 |
+
|
| 476 |
+
if j is a prime,
|
| 477 |
+
We remove all numbers(except j) whose
|
| 478 |
+
smallest prime factor is j.
|
| 479 |
+
|
| 480 |
+
Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
|
| 481 |
+
Now, after sieving from primes $\le j - 1$,
|
| 482 |
+
a must remain
|
| 483 |
+
(because x, and hence a has no prime factor $\le j - 1$)
|
| 484 |
+
Clearly, there are phi(i / j, j - 1) such a
|
| 485 |
+
which remain on sieving from primes $\le j - 1$
|
| 486 |
+
|
| 487 |
+
Now, if a is a prime less than equal to j - 1,
|
| 488 |
+
$x= j \times a$ has smallest prime factor = a, and
|
| 489 |
+
has already been removed(by sieving from a).
|
| 490 |
+
So, we do not need to remove it again.
|
| 491 |
+
(Note: there will be pi(j - 1) such x)
|
| 492 |
+
|
| 493 |
+
Thus, number of x, that will be removed are:
|
| 494 |
+
phi(i / j, j - 1) - phi(j - 1, j - 1)
|
| 495 |
+
(Note that pi(j - 1) = phi(j - 1, j - 1))
|
| 496 |
+
|
| 497 |
+
$\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
|
| 498 |
+
|
| 499 |
+
So,following recursion is used and implemented as dp:
|
| 500 |
+
|
| 501 |
+
phi(a, b) = phi(a, b - 1), if b is not a prime
|
| 502 |
+
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
|
| 503 |
+
|
| 504 |
+
Clearly a is always of the form floor(n / k),
|
| 505 |
+
which can take at most $2\sqrt{n}$ values.
|
| 506 |
+
Two arrays arr1,arr2 are maintained
|
| 507 |
+
arr1[i] = phi(i, j),
|
| 508 |
+
arr2[i] = phi(n // i, j)
|
| 509 |
+
|
| 510 |
+
Finally the answer is arr2[1]
|
| 511 |
+
|
| 512 |
+
Examples
|
| 513 |
+
========
|
| 514 |
+
|
| 515 |
+
>>> from sympy import primepi, prime, prevprime, isprime
|
| 516 |
+
>>> primepi(25)
|
| 517 |
+
9
|
| 518 |
+
|
| 519 |
+
So there are 9 primes less than or equal to 25. Is 25 prime?
|
| 520 |
+
|
| 521 |
+
>>> isprime(25)
|
| 522 |
+
False
|
| 523 |
+
|
| 524 |
+
It is not. So the first prime less than 25 must be the
|
| 525 |
+
9th prime:
|
| 526 |
+
|
| 527 |
+
>>> prevprime(25) == prime(9)
|
| 528 |
+
True
|
| 529 |
+
|
| 530 |
+
See Also
|
| 531 |
+
========
|
| 532 |
+
|
| 533 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
| 534 |
+
primerange : Generate all primes in a given range
|
| 535 |
+
prime : Return the nth prime
|
| 536 |
+
"""
|
| 537 |
+
from sympy.functions.combinatorial.numbers import primepi as func_primepi
|
| 538 |
+
return func_primepi(n)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _primepi(n:int) -> int:
|
| 542 |
+
r""" Represents the prime counting function pi(n) = the number
|
| 543 |
+
of prime numbers less than or equal to n.
|
| 544 |
+
|
| 545 |
+
Explanation
|
| 546 |
+
===========
|
| 547 |
+
|
| 548 |
+
In sieve method, we remove all multiples of prime p
|
| 549 |
+
except p itself.
|
| 550 |
+
|
| 551 |
+
Let phi(i,j) be the number of integers 2 <= k <= i
|
| 552 |
+
which remain after sieving from primes less than
|
| 553 |
+
or equal to j.
|
| 554 |
+
Clearly, pi(n) = phi(n, sqrt(n))
|
| 555 |
+
|
| 556 |
+
If j is not a prime,
|
| 557 |
+
phi(i,j) = phi(i, j - 1)
|
| 558 |
+
|
| 559 |
+
if j is a prime,
|
| 560 |
+
We remove all numbers(except j) whose
|
| 561 |
+
smallest prime factor is j.
|
| 562 |
+
|
| 563 |
+
Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
|
| 564 |
+
Now, after sieving from primes $\le j - 1$,
|
| 565 |
+
a must remain
|
| 566 |
+
(because x, and hence a has no prime factor $\le j - 1$)
|
| 567 |
+
Clearly, there are phi(i / j, j - 1) such a
|
| 568 |
+
which remain on sieving from primes $\le j - 1$
|
| 569 |
+
|
| 570 |
+
Now, if a is a prime less than equal to j - 1,
|
| 571 |
+
$x= j \times a$ has smallest prime factor = a, and
|
| 572 |
+
has already been removed(by sieving from a).
|
| 573 |
+
So, we do not need to remove it again.
|
| 574 |
+
(Note: there will be pi(j - 1) such x)
|
| 575 |
+
|
| 576 |
+
Thus, number of x, that will be removed are:
|
| 577 |
+
phi(i / j, j - 1) - phi(j - 1, j - 1)
|
| 578 |
+
(Note that pi(j - 1) = phi(j - 1, j - 1))
|
| 579 |
+
|
| 580 |
+
$\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
|
| 581 |
+
|
| 582 |
+
So,following recursion is used and implemented as dp:
|
| 583 |
+
|
| 584 |
+
phi(a, b) = phi(a, b - 1), if b is not a prime
|
| 585 |
+
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
|
| 586 |
+
|
| 587 |
+
Clearly a is always of the form floor(n / k),
|
| 588 |
+
which can take at most $2\sqrt{n}$ values.
|
| 589 |
+
Two arrays arr1,arr2 are maintained
|
| 590 |
+
arr1[i] = phi(i, j),
|
| 591 |
+
arr2[i] = phi(n // i, j)
|
| 592 |
+
|
| 593 |
+
Finally the answer is arr2[1]
|
| 594 |
+
|
| 595 |
+
Parameters
|
| 596 |
+
==========
|
| 597 |
+
|
| 598 |
+
n : int
|
| 599 |
+
|
| 600 |
+
"""
|
| 601 |
+
if n < 2:
|
| 602 |
+
return 0
|
| 603 |
+
if n <= sieve._list[-1]:
|
| 604 |
+
return sieve.search(n)[0]
|
| 605 |
+
lim = sqrt(n)
|
| 606 |
+
arr1 = [0] * (lim + 1)
|
| 607 |
+
arr2 = [0] * (lim + 1)
|
| 608 |
+
for i in range(1, lim + 1):
|
| 609 |
+
arr1[i] = i - 1
|
| 610 |
+
arr2[i] = n // i - 1
|
| 611 |
+
for i in range(2, lim + 1):
|
| 612 |
+
# Presently, arr1[k]=phi(k,i - 1),
|
| 613 |
+
# arr2[k] = phi(n // k,i - 1)
|
| 614 |
+
if arr1[i] == arr1[i - 1]:
|
| 615 |
+
continue
|
| 616 |
+
p = arr1[i - 1]
|
| 617 |
+
for j in range(1, min(n // (i * i), lim) + 1):
|
| 618 |
+
st = i * j
|
| 619 |
+
if st <= lim:
|
| 620 |
+
arr2[j] -= arr2[st] - p
|
| 621 |
+
else:
|
| 622 |
+
arr2[j] -= arr1[n // st] - p
|
| 623 |
+
lim2 = min(lim, i * i - 1)
|
| 624 |
+
for j in range(lim, lim2, -1):
|
| 625 |
+
arr1[j] -= arr1[j // i] - p
|
| 626 |
+
return arr2[1]
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def nextprime(n, ith=1):
|
| 630 |
+
""" Return the ith prime greater than n.
|
| 631 |
+
|
| 632 |
+
Parameters
|
| 633 |
+
==========
|
| 634 |
+
|
| 635 |
+
n : integer
|
| 636 |
+
ith : positive integer
|
| 637 |
+
|
| 638 |
+
Returns
|
| 639 |
+
=======
|
| 640 |
+
|
| 641 |
+
int : Return the ith prime greater than n
|
| 642 |
+
|
| 643 |
+
Raises
|
| 644 |
+
======
|
| 645 |
+
|
| 646 |
+
ValueError
|
| 647 |
+
If ``ith <= 0``.
|
| 648 |
+
If ``n`` or ``ith`` is not an integer.
|
| 649 |
+
|
| 650 |
+
Notes
|
| 651 |
+
=====
|
| 652 |
+
|
| 653 |
+
Potential primes are located at 6*j +/- 1. This
|
| 654 |
+
property is used during searching.
|
| 655 |
+
|
| 656 |
+
>>> from sympy import nextprime
|
| 657 |
+
>>> [(i, nextprime(i)) for i in range(10, 15)]
|
| 658 |
+
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
|
| 659 |
+
>>> nextprime(2, ith=2) # the 2nd prime after 2
|
| 660 |
+
5
|
| 661 |
+
|
| 662 |
+
See Also
|
| 663 |
+
========
|
| 664 |
+
|
| 665 |
+
prevprime : Return the largest prime smaller than n
|
| 666 |
+
primerange : Generate all primes in a given range
|
| 667 |
+
|
| 668 |
+
"""
|
| 669 |
+
n = int(n)
|
| 670 |
+
i = as_int(ith)
|
| 671 |
+
if i <= 0:
|
| 672 |
+
raise ValueError("ith should be positive")
|
| 673 |
+
if n < 2:
|
| 674 |
+
n = 2
|
| 675 |
+
i -= 1
|
| 676 |
+
if n <= sieve._list[-2]:
|
| 677 |
+
l, _ = sieve.search(n)
|
| 678 |
+
if l + i - 1 < len(sieve._list):
|
| 679 |
+
return sieve._list[l + i - 1]
|
| 680 |
+
return nextprime(sieve._list[-1], l + i - len(sieve._list))
|
| 681 |
+
if 1 < i:
|
| 682 |
+
for _ in range(i):
|
| 683 |
+
n = nextprime(n)
|
| 684 |
+
return n
|
| 685 |
+
nn = 6*(n//6)
|
| 686 |
+
if nn == n:
|
| 687 |
+
n += 1
|
| 688 |
+
if isprime(n):
|
| 689 |
+
return n
|
| 690 |
+
n += 4
|
| 691 |
+
elif n - nn == 5:
|
| 692 |
+
n += 2
|
| 693 |
+
if isprime(n):
|
| 694 |
+
return n
|
| 695 |
+
n += 4
|
| 696 |
+
else:
|
| 697 |
+
n = nn + 5
|
| 698 |
+
while 1:
|
| 699 |
+
if isprime(n):
|
| 700 |
+
return n
|
| 701 |
+
n += 2
|
| 702 |
+
if isprime(n):
|
| 703 |
+
return n
|
| 704 |
+
n += 4
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def prevprime(n):
|
| 708 |
+
""" Return the largest prime smaller than n.
|
| 709 |
+
|
| 710 |
+
Notes
|
| 711 |
+
=====
|
| 712 |
+
|
| 713 |
+
Potential primes are located at 6*j +/- 1. This
|
| 714 |
+
property is used during searching.
|
| 715 |
+
|
| 716 |
+
>>> from sympy import prevprime
|
| 717 |
+
>>> [(i, prevprime(i)) for i in range(10, 15)]
|
| 718 |
+
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
|
| 719 |
+
|
| 720 |
+
See Also
|
| 721 |
+
========
|
| 722 |
+
|
| 723 |
+
nextprime : Return the ith prime greater than n
|
| 724 |
+
primerange : Generates all primes in a given range
|
| 725 |
+
"""
|
| 726 |
+
n = _as_int_ceiling(n)
|
| 727 |
+
if n < 3:
|
| 728 |
+
raise ValueError("no preceding primes")
|
| 729 |
+
if n < 8:
|
| 730 |
+
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
|
| 731 |
+
if n <= sieve._list[-1]:
|
| 732 |
+
l, u = sieve.search(n)
|
| 733 |
+
if l == u:
|
| 734 |
+
return sieve[l-1]
|
| 735 |
+
else:
|
| 736 |
+
return sieve[l]
|
| 737 |
+
nn = 6*(n//6)
|
| 738 |
+
if n - nn <= 1:
|
| 739 |
+
n = nn - 1
|
| 740 |
+
if isprime(n):
|
| 741 |
+
return n
|
| 742 |
+
n -= 4
|
| 743 |
+
else:
|
| 744 |
+
n = nn + 1
|
| 745 |
+
while 1:
|
| 746 |
+
if isprime(n):
|
| 747 |
+
return n
|
| 748 |
+
n -= 2
|
| 749 |
+
if isprime(n):
|
| 750 |
+
return n
|
| 751 |
+
n -= 4
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def primerange(a, b=None):
|
| 755 |
+
""" Generate a list of all prime numbers in the range [2, a),
|
| 756 |
+
or [a, b).
|
| 757 |
+
|
| 758 |
+
If the range exists in the default sieve, the values will
|
| 759 |
+
be returned from there; otherwise values will be returned
|
| 760 |
+
but will not modify the sieve.
|
| 761 |
+
|
| 762 |
+
Examples
|
| 763 |
+
========
|
| 764 |
+
|
| 765 |
+
>>> from sympy import primerange, prime
|
| 766 |
+
|
| 767 |
+
All primes less than 19:
|
| 768 |
+
|
| 769 |
+
>>> list(primerange(19))
|
| 770 |
+
[2, 3, 5, 7, 11, 13, 17]
|
| 771 |
+
|
| 772 |
+
All primes greater than or equal to 7 and less than 19:
|
| 773 |
+
|
| 774 |
+
>>> list(primerange(7, 19))
|
| 775 |
+
[7, 11, 13, 17]
|
| 776 |
+
|
| 777 |
+
All primes through the 10th prime
|
| 778 |
+
|
| 779 |
+
>>> list(primerange(prime(10) + 1))
|
| 780 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
| 781 |
+
|
| 782 |
+
The Sieve method, primerange, is generally faster but it will
|
| 783 |
+
occupy more memory as the sieve stores values. The default
|
| 784 |
+
instance of Sieve, named sieve, can be used:
|
| 785 |
+
|
| 786 |
+
>>> from sympy import sieve
|
| 787 |
+
>>> list(sieve.primerange(1, 30))
|
| 788 |
+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
| 789 |
+
|
| 790 |
+
Notes
|
| 791 |
+
=====
|
| 792 |
+
|
| 793 |
+
Some famous conjectures about the occurrence of primes in a given
|
| 794 |
+
range are [1]:
|
| 795 |
+
|
| 796 |
+
- Twin primes: though often not, the following will give 2 primes
|
| 797 |
+
an infinite number of times:
|
| 798 |
+
primerange(6*n - 1, 6*n + 2)
|
| 799 |
+
- Legendre's: the following always yields at least one prime
|
| 800 |
+
primerange(n**2, (n+1)**2+1)
|
| 801 |
+
- Bertrand's (proven): there is always a prime in the range
|
| 802 |
+
primerange(n, 2*n)
|
| 803 |
+
- Brocard's: there are at least four primes in the range
|
| 804 |
+
primerange(prime(n)**2, prime(n+1)**2)
|
| 805 |
+
|
| 806 |
+
The average gap between primes is log(n) [2]; the gap between
|
| 807 |
+
primes can be arbitrarily large since sequences of composite
|
| 808 |
+
numbers are arbitrarily large, e.g. the numbers in the sequence
|
| 809 |
+
n! + 2, n! + 3 ... n! + n are all composite.
|
| 810 |
+
|
| 811 |
+
See Also
|
| 812 |
+
========
|
| 813 |
+
|
| 814 |
+
prime : Return the nth prime
|
| 815 |
+
nextprime : Return the ith prime greater than n
|
| 816 |
+
prevprime : Return the largest prime smaller than n
|
| 817 |
+
randprime : Returns a random prime in a given range
|
| 818 |
+
primorial : Returns the product of primes based on condition
|
| 819 |
+
Sieve.primerange : return range from already computed primes
|
| 820 |
+
or extend the sieve to contain the requested
|
| 821 |
+
range.
|
| 822 |
+
|
| 823 |
+
References
|
| 824 |
+
==========
|
| 825 |
+
|
| 826 |
+
.. [1] https://en.wikipedia.org/wiki/Prime_number
|
| 827 |
+
.. [2] https://primes.utm.edu/notes/gaps.html
|
| 828 |
+
"""
|
| 829 |
+
if b is None:
|
| 830 |
+
a, b = 2, a
|
| 831 |
+
if a >= b:
|
| 832 |
+
return
|
| 833 |
+
# If we already have the range, return it.
|
| 834 |
+
largest_known_prime = sieve._list[-1]
|
| 835 |
+
if b <= largest_known_prime:
|
| 836 |
+
yield from sieve.primerange(a, b)
|
| 837 |
+
return
|
| 838 |
+
# If we know some of it, return it.
|
| 839 |
+
if a <= largest_known_prime:
|
| 840 |
+
yield from sieve._list[bisect_left(sieve._list, a):]
|
| 841 |
+
a = largest_known_prime + 1
|
| 842 |
+
elif a % 2:
|
| 843 |
+
a -= 1
|
| 844 |
+
tail = min(b, (largest_known_prime)**2)
|
| 845 |
+
if a < tail:
|
| 846 |
+
yield from sieve._primerange(a, tail)
|
| 847 |
+
a = tail
|
| 848 |
+
if b <= a:
|
| 849 |
+
return
|
| 850 |
+
# otherwise compute, without storing, the desired range.
|
| 851 |
+
while 1:
|
| 852 |
+
a = nextprime(a)
|
| 853 |
+
if a < b:
|
| 854 |
+
yield a
|
| 855 |
+
else:
|
| 856 |
+
return
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def randprime(a, b):
|
| 860 |
+
""" Return a random prime number in the range [a, b).
|
| 861 |
+
|
| 862 |
+
Bertrand's postulate assures that
|
| 863 |
+
randprime(a, 2*a) will always succeed for a > 1.
|
| 864 |
+
|
| 865 |
+
Note that due to implementation difficulties,
|
| 866 |
+
the prime numbers chosen are not uniformly random.
|
| 867 |
+
For example, there are two primes in the range [112, 128),
|
| 868 |
+
``113`` and ``127``, but ``randprime(112, 128)`` returns ``127``
|
| 869 |
+
with a probability of 15/17.
|
| 870 |
+
|
| 871 |
+
Examples
|
| 872 |
+
========
|
| 873 |
+
|
| 874 |
+
>>> from sympy import randprime, isprime
|
| 875 |
+
>>> randprime(1, 30) #doctest: +SKIP
|
| 876 |
+
13
|
| 877 |
+
>>> isprime(randprime(1, 30))
|
| 878 |
+
True
|
| 879 |
+
|
| 880 |
+
See Also
|
| 881 |
+
========
|
| 882 |
+
|
| 883 |
+
primerange : Generate all primes in a given range
|
| 884 |
+
|
| 885 |
+
References
|
| 886 |
+
==========
|
| 887 |
+
|
| 888 |
+
.. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
|
| 889 |
+
|
| 890 |
+
"""
|
| 891 |
+
if a >= b:
|
| 892 |
+
return
|
| 893 |
+
a, b = map(int, (a, b))
|
| 894 |
+
n = randint(a - 1, b)
|
| 895 |
+
p = nextprime(n)
|
| 896 |
+
if p >= b:
|
| 897 |
+
p = prevprime(b)
|
| 898 |
+
if p < a:
|
| 899 |
+
raise ValueError("no primes exist in the specified range")
|
| 900 |
+
return p
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def primorial(n, nth=True):
|
| 904 |
+
"""
|
| 905 |
+
Returns the product of the first n primes (default) or
|
| 906 |
+
the primes less than or equal to n (when ``nth=False``).
|
| 907 |
+
|
| 908 |
+
Examples
|
| 909 |
+
========
|
| 910 |
+
|
| 911 |
+
>>> from sympy.ntheory.generate import primorial, primerange
|
| 912 |
+
>>> from sympy import factorint, Mul, primefactors, sqrt
|
| 913 |
+
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
|
| 914 |
+
210
|
| 915 |
+
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
|
| 916 |
+
6
|
| 917 |
+
>>> primorial(1)
|
| 918 |
+
2
|
| 919 |
+
>>> primorial(1, nth=False)
|
| 920 |
+
1
|
| 921 |
+
>>> primorial(sqrt(101), nth=False)
|
| 922 |
+
210
|
| 923 |
+
|
| 924 |
+
One can argue that the primes are infinite since if you take
|
| 925 |
+
a set of primes and multiply them together (e.g. the primorial) and
|
| 926 |
+
then add or subtract 1, the result cannot be divided by any of the
|
| 927 |
+
original factors, hence either 1 or more new primes must divide this
|
| 928 |
+
product of primes.
|
| 929 |
+
|
| 930 |
+
In this case, the number itself is a new prime:
|
| 931 |
+
|
| 932 |
+
>>> factorint(primorial(4) + 1)
|
| 933 |
+
{211: 1}
|
| 934 |
+
|
| 935 |
+
In this case two new primes are the factors:
|
| 936 |
+
|
| 937 |
+
>>> factorint(primorial(4) - 1)
|
| 938 |
+
{11: 1, 19: 1}
|
| 939 |
+
|
| 940 |
+
Here, some primes smaller and larger than the primes multiplied together
|
| 941 |
+
are obtained:
|
| 942 |
+
|
| 943 |
+
>>> p = list(primerange(10, 20))
|
| 944 |
+
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
|
| 945 |
+
[2, 5, 31, 149]
|
| 946 |
+
|
| 947 |
+
See Also
|
| 948 |
+
========
|
| 949 |
+
|
| 950 |
+
primerange : Generate all primes in a given range
|
| 951 |
+
|
| 952 |
+
"""
|
| 953 |
+
if nth:
|
| 954 |
+
n = as_int(n)
|
| 955 |
+
else:
|
| 956 |
+
n = int(n)
|
| 957 |
+
if n < 1:
|
| 958 |
+
raise ValueError("primorial argument must be >= 1")
|
| 959 |
+
p = 1
|
| 960 |
+
if nth:
|
| 961 |
+
for i in range(1, n + 1):
|
| 962 |
+
p *= prime(i)
|
| 963 |
+
else:
|
| 964 |
+
for i in primerange(2, n + 1):
|
| 965 |
+
p *= i
|
| 966 |
+
return p
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def cycle_length(f, x0, nmax=None, values=False):
|
| 970 |
+
"""For a given iterated sequence, return a generator that gives
|
| 971 |
+
the length of the iterated cycle (lambda) and the length of terms
|
| 972 |
+
before the cycle begins (mu); if ``values`` is True then the
|
| 973 |
+
terms of the sequence will be returned instead. The sequence is
|
| 974 |
+
started with value ``x0``.
|
| 975 |
+
|
| 976 |
+
Note: more than the first lambda + mu terms may be returned and this
|
| 977 |
+
is the cost of cycle detection with Brent's method; there are, however,
|
| 978 |
+
generally less terms calculated than would have been calculated if the
|
| 979 |
+
proper ending point were determined, e.g. by using Floyd's method.
|
| 980 |
+
|
| 981 |
+
>>> from sympy.ntheory.generate import cycle_length
|
| 982 |
+
|
| 983 |
+
This will yield successive values of i <-- func(i):
|
| 984 |
+
|
| 985 |
+
>>> def gen(func, i):
|
| 986 |
+
... while 1:
|
| 987 |
+
... yield i
|
| 988 |
+
... i = func(i)
|
| 989 |
+
...
|
| 990 |
+
|
| 991 |
+
A function is defined:
|
| 992 |
+
|
| 993 |
+
>>> func = lambda i: (i**2 + 1) % 51
|
| 994 |
+
|
| 995 |
+
and given a seed of 4 and the mu and lambda terms calculated:
|
| 996 |
+
|
| 997 |
+
>>> next(cycle_length(func, 4))
|
| 998 |
+
(6, 3)
|
| 999 |
+
|
| 1000 |
+
We can see what is meant by looking at the output:
|
| 1001 |
+
|
| 1002 |
+
>>> iter = cycle_length(func, 4, values=True)
|
| 1003 |
+
>>> list(iter)
|
| 1004 |
+
[4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
|
| 1005 |
+
|
| 1006 |
+
There are 6 repeating values after the first 3.
|
| 1007 |
+
|
| 1008 |
+
If a sequence is suspected of being longer than you might wish, ``nmax``
|
| 1009 |
+
can be used to exit early (and mu will be returned as None):
|
| 1010 |
+
|
| 1011 |
+
>>> next(cycle_length(func, 4, nmax = 4))
|
| 1012 |
+
(4, None)
|
| 1013 |
+
>>> list(cycle_length(func, 4, nmax = 4, values=True))
|
| 1014 |
+
[4, 17, 35, 2]
|
| 1015 |
+
|
| 1016 |
+
Code modified from:
|
| 1017 |
+
https://en.wikipedia.org/wiki/Cycle_detection.
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
nmax = int(nmax or 0)
|
| 1021 |
+
|
| 1022 |
+
# main phase: search successive powers of two
|
| 1023 |
+
power = lam = 1
|
| 1024 |
+
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
|
| 1025 |
+
i = 1
|
| 1026 |
+
if values:
|
| 1027 |
+
yield tortoise
|
| 1028 |
+
while tortoise != hare and (not nmax or i < nmax):
|
| 1029 |
+
i += 1
|
| 1030 |
+
if power == lam: # time to start a new power of two?
|
| 1031 |
+
tortoise = hare
|
| 1032 |
+
power *= 2
|
| 1033 |
+
lam = 0
|
| 1034 |
+
if values:
|
| 1035 |
+
yield hare
|
| 1036 |
+
hare = f(hare)
|
| 1037 |
+
lam += 1
|
| 1038 |
+
if nmax and i == nmax:
|
| 1039 |
+
if values:
|
| 1040 |
+
return
|
| 1041 |
+
else:
|
| 1042 |
+
yield nmax, None
|
| 1043 |
+
return
|
| 1044 |
+
if not values:
|
| 1045 |
+
# Find the position of the first repetition of length lambda
|
| 1046 |
+
mu = 0
|
| 1047 |
+
tortoise = hare = x0
|
| 1048 |
+
for i in range(lam):
|
| 1049 |
+
hare = f(hare)
|
| 1050 |
+
while tortoise != hare:
|
| 1051 |
+
tortoise = f(tortoise)
|
| 1052 |
+
hare = f(hare)
|
| 1053 |
+
mu += 1
|
| 1054 |
+
yield lam, mu
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def composite(nth):
|
| 1058 |
+
""" Return the nth composite number, with the composite numbers indexed as
|
| 1059 |
+
composite(1) = 4, composite(2) = 6, etc....
|
| 1060 |
+
|
| 1061 |
+
Examples
|
| 1062 |
+
========
|
| 1063 |
+
|
| 1064 |
+
>>> from sympy import composite
|
| 1065 |
+
>>> composite(36)
|
| 1066 |
+
52
|
| 1067 |
+
>>> composite(1)
|
| 1068 |
+
4
|
| 1069 |
+
>>> composite(17737)
|
| 1070 |
+
20000
|
| 1071 |
+
|
| 1072 |
+
See Also
|
| 1073 |
+
========
|
| 1074 |
+
|
| 1075 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
| 1076 |
+
primerange : Generate all primes in a given range
|
| 1077 |
+
primepi : Return the number of primes less than or equal to n
|
| 1078 |
+
prime : Return the nth prime
|
| 1079 |
+
compositepi : Return the number of positive composite numbers less than or equal to n
|
| 1080 |
+
"""
|
| 1081 |
+
n = as_int(nth)
|
| 1082 |
+
if n < 1:
|
| 1083 |
+
raise ValueError("nth must be a positive integer; composite(1) == 4")
|
| 1084 |
+
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
|
| 1085 |
+
if n <= 10:
|
| 1086 |
+
return composite_arr[n - 1]
|
| 1087 |
+
|
| 1088 |
+
a, b = 4, sieve._list[-1]
|
| 1089 |
+
if n <= b - _primepi(b) - 1:
|
| 1090 |
+
while a < b - 1:
|
| 1091 |
+
mid = (a + b) >> 1
|
| 1092 |
+
if mid - _primepi(mid) - 1 > n:
|
| 1093 |
+
b = mid
|
| 1094 |
+
else:
|
| 1095 |
+
a = mid
|
| 1096 |
+
if isprime(a):
|
| 1097 |
+
a -= 1
|
| 1098 |
+
return a
|
| 1099 |
+
|
| 1100 |
+
from sympy.functions.elementary.exponential import log
|
| 1101 |
+
from sympy.functions.special.error_functions import li
|
| 1102 |
+
a = 4 # Lower bound for binary search
|
| 1103 |
+
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
|
| 1104 |
+
|
| 1105 |
+
while a < b:
|
| 1106 |
+
mid = (a + b) >> 1
|
| 1107 |
+
if mid - li(mid) - 1 > n:
|
| 1108 |
+
b = mid
|
| 1109 |
+
else:
|
| 1110 |
+
a = mid + 1
|
| 1111 |
+
|
| 1112 |
+
n_composites = a - _primepi(a) - 1
|
| 1113 |
+
while n_composites > n:
|
| 1114 |
+
if not isprime(a):
|
| 1115 |
+
n_composites -= 1
|
| 1116 |
+
a -= 1
|
| 1117 |
+
if isprime(a):
|
| 1118 |
+
a -= 1
|
| 1119 |
+
return a
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
def compositepi(n):
|
| 1123 |
+
""" Return the number of positive composite numbers less than or equal to n.
|
| 1124 |
+
The first positive composite is 4, i.e. compositepi(4) = 1.
|
| 1125 |
+
|
| 1126 |
+
Examples
|
| 1127 |
+
========
|
| 1128 |
+
|
| 1129 |
+
>>> from sympy import compositepi
|
| 1130 |
+
>>> compositepi(25)
|
| 1131 |
+
15
|
| 1132 |
+
>>> compositepi(1000)
|
| 1133 |
+
831
|
| 1134 |
+
|
| 1135 |
+
See Also
|
| 1136 |
+
========
|
| 1137 |
+
|
| 1138 |
+
sympy.ntheory.primetest.isprime : Test if n is prime
|
| 1139 |
+
primerange : Generate all primes in a given range
|
| 1140 |
+
prime : Return the nth prime
|
| 1141 |
+
primepi : Return the number of primes less than or equal to n
|
| 1142 |
+
composite : Return the nth composite number
|
| 1143 |
+
"""
|
| 1144 |
+
n = int(n)
|
| 1145 |
+
if n < 4:
|
| 1146 |
+
return 0
|
| 1147 |
+
return n - _primepi(n) - 1
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/primetest.py
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Primality testing
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from itertools import count
|
| 7 |
+
|
| 8 |
+
from sympy.core.sympify import sympify
|
| 9 |
+
from sympy.external.gmpy import (gmpy as _gmpy, gcd, jacobi,
|
| 10 |
+
is_square as gmpy_is_square,
|
| 11 |
+
bit_scan1, is_fermat_prp, is_euler_prp,
|
| 12 |
+
is_selfridge_prp, is_strong_selfridge_prp,
|
| 13 |
+
is_strong_bpsw_prp)
|
| 14 |
+
from sympy.external.ntheory import _lucas_sequence
|
| 15 |
+
from sympy.utilities.misc import as_int, filldedent
|
| 16 |
+
|
| 17 |
+
# Note: This list should be updated whenever new Mersenne primes are found.
|
| 18 |
+
# Refer: https://www.mersenne.org/
|
| 19 |
+
MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
|
| 20 |
+
2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
|
| 21 |
+
216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
|
| 22 |
+
25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def is_fermat_pseudoprime(n, a):
|
| 26 |
+
r"""Returns True if ``n`` is prime or is an odd composite integer that
|
| 27 |
+
is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
|
| 28 |
+
|
| 29 |
+
.. math ::
|
| 30 |
+
a^{n-1} \equiv 1 \pmod{n}
|
| 31 |
+
|
| 32 |
+
(where mod refers to the modulo operation).
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
==========
|
| 36 |
+
|
| 37 |
+
n : Integer
|
| 38 |
+
``n`` is a positive integer.
|
| 39 |
+
a : Integer
|
| 40 |
+
``a`` is a positive integer.
|
| 41 |
+
``a`` and ``n`` should be relatively prime.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
=======
|
| 45 |
+
|
| 46 |
+
bool : If ``n`` is prime, it always returns ``True``.
|
| 47 |
+
The composite number that returns ``True`` is called an Fermat pseudoprime.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy.ntheory.primetest import is_fermat_pseudoprime
|
| 53 |
+
>>> from sympy.ntheory.factor_ import isprime
|
| 54 |
+
>>> for n in range(1, 1000):
|
| 55 |
+
... if is_fermat_pseudoprime(n, 2) and not isprime(n):
|
| 56 |
+
... print(n)
|
| 57 |
+
341
|
| 58 |
+
561
|
| 59 |
+
645
|
| 60 |
+
|
| 61 |
+
References
|
| 62 |
+
==========
|
| 63 |
+
|
| 64 |
+
.. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
|
| 65 |
+
"""
|
| 66 |
+
n, a = as_int(n), as_int(a)
|
| 67 |
+
if a == 1:
|
| 68 |
+
return n == 2 or bool(n % 2)
|
| 69 |
+
return is_fermat_prp(n, a)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def is_euler_pseudoprime(n, a):
|
| 73 |
+
r"""Returns True if ``n`` is prime or is an odd composite integer that
|
| 74 |
+
is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
|
| 75 |
+
|
| 76 |
+
.. math ::
|
| 77 |
+
a^{(n-1)/2} \equiv \pm 1 \pmod{n}
|
| 78 |
+
|
| 79 |
+
(where mod refers to the modulo operation).
|
| 80 |
+
|
| 81 |
+
Parameters
|
| 82 |
+
==========
|
| 83 |
+
|
| 84 |
+
n : Integer
|
| 85 |
+
``n`` is a positive integer.
|
| 86 |
+
a : Integer
|
| 87 |
+
``a`` is a positive integer.
|
| 88 |
+
``a`` and ``n`` should be relatively prime.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
=======
|
| 92 |
+
|
| 93 |
+
bool : If ``n`` is prime, it always returns ``True``.
|
| 94 |
+
The composite number that returns ``True`` is called an Euler pseudoprime.
|
| 95 |
+
|
| 96 |
+
Examples
|
| 97 |
+
========
|
| 98 |
+
|
| 99 |
+
>>> from sympy.ntheory.primetest import is_euler_pseudoprime
|
| 100 |
+
>>> from sympy.ntheory.factor_ import isprime
|
| 101 |
+
>>> for n in range(1, 1000):
|
| 102 |
+
... if is_euler_pseudoprime(n, 2) and not isprime(n):
|
| 103 |
+
... print(n)
|
| 104 |
+
341
|
| 105 |
+
561
|
| 106 |
+
|
| 107 |
+
References
|
| 108 |
+
==========
|
| 109 |
+
|
| 110 |
+
.. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
|
| 111 |
+
"""
|
| 112 |
+
n, a = as_int(n), as_int(a)
|
| 113 |
+
if a < 1:
|
| 114 |
+
raise ValueError("a should be an integer greater than 0")
|
| 115 |
+
if n < 1:
|
| 116 |
+
raise ValueError("n should be an integer greater than 0")
|
| 117 |
+
if n == 1:
|
| 118 |
+
return False
|
| 119 |
+
if a == 1:
|
| 120 |
+
return n == 2 or bool(n % 2) # (prime or odd composite)
|
| 121 |
+
if n % 2 == 0:
|
| 122 |
+
return n == 2
|
| 123 |
+
if gcd(n, a) != 1:
|
| 124 |
+
raise ValueError("The two numbers should be relatively prime")
|
| 125 |
+
return pow(a, (n - 1) // 2, n) in [1, n - 1]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def is_euler_jacobi_pseudoprime(n, a):
|
| 129 |
+
r"""Returns True if ``n`` is prime or is an odd composite integer that
|
| 130 |
+
is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
|
| 131 |
+
|
| 132 |
+
.. math ::
|
| 133 |
+
a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}
|
| 134 |
+
|
| 135 |
+
(where mod refers to the modulo operation).
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
==========
|
| 139 |
+
|
| 140 |
+
n : Integer
|
| 141 |
+
``n`` is a positive integer.
|
| 142 |
+
a : Integer
|
| 143 |
+
``a`` is a positive integer.
|
| 144 |
+
``a`` and ``n`` should be relatively prime.
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
=======
|
| 148 |
+
|
| 149 |
+
bool : If ``n`` is prime, it always returns ``True``.
|
| 150 |
+
The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.
|
| 151 |
+
|
| 152 |
+
Examples
|
| 153 |
+
========
|
| 154 |
+
|
| 155 |
+
>>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
|
| 156 |
+
>>> from sympy.ntheory.factor_ import isprime
|
| 157 |
+
>>> for n in range(1, 1000):
|
| 158 |
+
... if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
|
| 159 |
+
... print(n)
|
| 160 |
+
561
|
| 161 |
+
|
| 162 |
+
References
|
| 163 |
+
==========
|
| 164 |
+
|
| 165 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
|
| 166 |
+
"""
|
| 167 |
+
n, a = as_int(n), as_int(a)
|
| 168 |
+
if a == 1:
|
| 169 |
+
return n == 2 or bool(n % 2)
|
| 170 |
+
return is_euler_prp(n, a)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def is_square(n, prep=True):
|
| 174 |
+
"""Return True if n == a * a for some integer a, else False.
|
| 175 |
+
If n is suspected of *not* being a square then this is a
|
| 176 |
+
quick method of confirming that it is not.
|
| 177 |
+
|
| 178 |
+
Examples
|
| 179 |
+
========
|
| 180 |
+
|
| 181 |
+
>>> from sympy.ntheory.primetest import is_square
|
| 182 |
+
>>> is_square(25)
|
| 183 |
+
True
|
| 184 |
+
>>> is_square(2)
|
| 185 |
+
False
|
| 186 |
+
|
| 187 |
+
References
|
| 188 |
+
==========
|
| 189 |
+
|
| 190 |
+
.. [1] https://mersenneforum.org/showpost.php?p=110896
|
| 191 |
+
|
| 192 |
+
See Also
|
| 193 |
+
========
|
| 194 |
+
sympy.core.intfunc.isqrt
|
| 195 |
+
"""
|
| 196 |
+
if prep:
|
| 197 |
+
n = as_int(n)
|
| 198 |
+
if n < 0:
|
| 199 |
+
return False
|
| 200 |
+
if n in (0, 1):
|
| 201 |
+
return True
|
| 202 |
+
return gmpy_is_square(n)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _test(n, base, s, t):
|
| 206 |
+
"""Miller-Rabin strong pseudoprime test for one base.
|
| 207 |
+
Return False if n is definitely composite, True if n is
|
| 208 |
+
probably prime, with a probability greater than 3/4.
|
| 209 |
+
|
| 210 |
+
"""
|
| 211 |
+
# do the Fermat test
|
| 212 |
+
b = pow(base, t, n)
|
| 213 |
+
if b == 1 or b == n - 1:
|
| 214 |
+
return True
|
| 215 |
+
for _ in range(s - 1):
|
| 216 |
+
b = pow(b, 2, n)
|
| 217 |
+
if b == n - 1:
|
| 218 |
+
return True
|
| 219 |
+
# see I. Niven et al. "An Introduction to Theory of Numbers", page 78
|
| 220 |
+
if b == 1:
|
| 221 |
+
return False
|
| 222 |
+
return False
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def mr(n, bases):
|
| 226 |
+
"""Perform a Miller-Rabin strong pseudoprime test on n using a
|
| 227 |
+
given list of bases/witnesses.
|
| 228 |
+
|
| 229 |
+
References
|
| 230 |
+
==========
|
| 231 |
+
|
| 232 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
| 233 |
+
A Computational Perspective", Springer, 2nd edition, 135-138
|
| 234 |
+
|
| 235 |
+
A list of thresholds and the bases they require are here:
|
| 236 |
+
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
|
| 237 |
+
|
| 238 |
+
Examples
|
| 239 |
+
========
|
| 240 |
+
|
| 241 |
+
>>> from sympy.ntheory.primetest import mr
|
| 242 |
+
>>> mr(1373651, [2, 3])
|
| 243 |
+
False
|
| 244 |
+
>>> mr(479001599, [31, 73])
|
| 245 |
+
True
|
| 246 |
+
|
| 247 |
+
"""
|
| 248 |
+
from sympy.polys.domains import ZZ
|
| 249 |
+
|
| 250 |
+
n = as_int(n)
|
| 251 |
+
if n < 2:
|
| 252 |
+
return False
|
| 253 |
+
# remove powers of 2 from n-1 (= t * 2**s)
|
| 254 |
+
s = bit_scan1(n - 1)
|
| 255 |
+
t = n >> s
|
| 256 |
+
for base in bases:
|
| 257 |
+
# Bases >= n are wrapped, bases < 2 are invalid
|
| 258 |
+
if base >= n:
|
| 259 |
+
base %= n
|
| 260 |
+
if base >= 2:
|
| 261 |
+
base = ZZ(base)
|
| 262 |
+
if not _test(n, base, s, t):
|
| 263 |
+
return False
|
| 264 |
+
return True
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _lucas_extrastrong_params(n):
|
| 268 |
+
"""Calculates the "extra strong" parameters (D, P, Q) for n.
|
| 269 |
+
|
| 270 |
+
Parameters
|
| 271 |
+
==========
|
| 272 |
+
|
| 273 |
+
n : int
|
| 274 |
+
positive odd integer
|
| 275 |
+
|
| 276 |
+
Returns
|
| 277 |
+
=======
|
| 278 |
+
|
| 279 |
+
D, P, Q: "extra strong" parameters.
|
| 280 |
+
``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.
|
| 281 |
+
|
| 282 |
+
Examples
|
| 283 |
+
========
|
| 284 |
+
|
| 285 |
+
>>> from sympy.ntheory.primetest import _lucas_extrastrong_params
|
| 286 |
+
>>> _lucas_extrastrong_params(101)
|
| 287 |
+
(12, 4, 1)
|
| 288 |
+
>>> _lucas_extrastrong_params(15)
|
| 289 |
+
(0, 0, 0)
|
| 290 |
+
|
| 291 |
+
References
|
| 292 |
+
==========
|
| 293 |
+
.. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
|
| 294 |
+
https://oeis.org/A217719
|
| 295 |
+
.. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
| 296 |
+
|
| 297 |
+
"""
|
| 298 |
+
for P in count(3):
|
| 299 |
+
D = P**2 - 4
|
| 300 |
+
j = jacobi(D, n)
|
| 301 |
+
if j == -1:
|
| 302 |
+
return (D, P, 1)
|
| 303 |
+
elif j == 0 and D % n:
|
| 304 |
+
return (0, 0, 0)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def is_lucas_prp(n):
|
| 308 |
+
"""Standard Lucas compositeness test with Selfridge parameters. Returns
|
| 309 |
+
False if n is definitely composite, and True if n is a Lucas probable
|
| 310 |
+
prime.
|
| 311 |
+
|
| 312 |
+
This is typically used in combination with the Miller-Rabin test.
|
| 313 |
+
|
| 314 |
+
References
|
| 315 |
+
==========
|
| 316 |
+
.. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
|
| 317 |
+
Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
|
| 318 |
+
https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
|
| 319 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
| 320 |
+
.. [2] OEIS A217120: Lucas Pseudoprimes
|
| 321 |
+
https://oeis.org/A217120
|
| 322 |
+
.. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
| 323 |
+
|
| 324 |
+
Examples
|
| 325 |
+
========
|
| 326 |
+
|
| 327 |
+
>>> from sympy.ntheory.primetest import isprime, is_lucas_prp
|
| 328 |
+
>>> for i in range(10000):
|
| 329 |
+
... if is_lucas_prp(i) and not isprime(i):
|
| 330 |
+
... print(i)
|
| 331 |
+
323
|
| 332 |
+
377
|
| 333 |
+
1159
|
| 334 |
+
1829
|
| 335 |
+
3827
|
| 336 |
+
5459
|
| 337 |
+
5777
|
| 338 |
+
9071
|
| 339 |
+
9179
|
| 340 |
+
"""
|
| 341 |
+
n = as_int(n)
|
| 342 |
+
if n < 2:
|
| 343 |
+
return False
|
| 344 |
+
return is_selfridge_prp(n)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def is_strong_lucas_prp(n):
|
| 348 |
+
"""Strong Lucas compositeness test with Selfridge parameters. Returns
|
| 349 |
+
False if n is definitely composite, and True if n is a strong Lucas
|
| 350 |
+
probable prime.
|
| 351 |
+
|
| 352 |
+
This is often used in combination with the Miller-Rabin test, and
|
| 353 |
+
in particular, when combined with M-R base 2 creates the strong BPSW test.
|
| 354 |
+
|
| 355 |
+
References
|
| 356 |
+
==========
|
| 357 |
+
.. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
|
| 358 |
+
Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
|
| 359 |
+
https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
|
| 360 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
| 361 |
+
.. [2] OEIS A217255: Strong Lucas Pseudoprimes
|
| 362 |
+
https://oeis.org/A217255
|
| 363 |
+
.. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
| 364 |
+
.. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
|
| 365 |
+
|
| 366 |
+
Examples
|
| 367 |
+
========
|
| 368 |
+
|
| 369 |
+
>>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
|
| 370 |
+
>>> for i in range(20000):
|
| 371 |
+
... if is_strong_lucas_prp(i) and not isprime(i):
|
| 372 |
+
... print(i)
|
| 373 |
+
5459
|
| 374 |
+
5777
|
| 375 |
+
10877
|
| 376 |
+
16109
|
| 377 |
+
18971
|
| 378 |
+
"""
|
| 379 |
+
n = as_int(n)
|
| 380 |
+
if n < 2:
|
| 381 |
+
return False
|
| 382 |
+
return is_strong_selfridge_prp(n)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def is_extra_strong_lucas_prp(n):
|
| 386 |
+
"""Extra Strong Lucas compositeness test. Returns False if n is
|
| 387 |
+
definitely composite, and True if n is an "extra strong" Lucas probable
|
| 388 |
+
prime.
|
| 389 |
+
|
| 390 |
+
The parameters are selected using P = 3, Q = 1, then incrementing P until
|
| 391 |
+
(D|n) == -1. The test itself is as defined in [1]_, from the
|
| 392 |
+
Mo and Jones preprint. The parameter selection and test are the same as
|
| 393 |
+
used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
|
| 394 |
+
page on Wikipedia.
|
| 395 |
+
|
| 396 |
+
It is 20-50% faster than the strong test.
|
| 397 |
+
|
| 398 |
+
Because of the different parameters selected, there is no relationship
|
| 399 |
+
between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
|
| 400 |
+
In particular, one is not a subset of the other.
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
==========
|
| 404 |
+
.. [1] Jon Grantham, Frobenius Pseudoprimes,
|
| 405 |
+
Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
|
| 406 |
+
https://doi.org/10.1090%2FS0025-5718-00-01197-2
|
| 407 |
+
.. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
|
| 408 |
+
https://oeis.org/A217719
|
| 409 |
+
.. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
|
| 410 |
+
|
| 411 |
+
Examples
|
| 412 |
+
========
|
| 413 |
+
|
| 414 |
+
>>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
|
| 415 |
+
>>> for i in range(20000):
|
| 416 |
+
... if is_extra_strong_lucas_prp(i) and not isprime(i):
|
| 417 |
+
... print(i)
|
| 418 |
+
989
|
| 419 |
+
3239
|
| 420 |
+
5777
|
| 421 |
+
10877
|
| 422 |
+
"""
|
| 423 |
+
# Implementation notes:
|
| 424 |
+
# 1) the parameters differ from Thomas R. Nicely's. His parameter
|
| 425 |
+
# selection leads to pseudoprimes that overlap M-R tests, and
|
| 426 |
+
# contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
|
| 427 |
+
# 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
|
| 428 |
+
# sequence must have Q=1. See Grantham theorem 2.3, any of the
|
| 429 |
+
# references on the MathWorld page, or run it and see Q=-1 is wrong.
|
| 430 |
+
n = as_int(n)
|
| 431 |
+
if n == 2:
|
| 432 |
+
return True
|
| 433 |
+
if n < 2 or (n % 2) == 0:
|
| 434 |
+
return False
|
| 435 |
+
if gmpy_is_square(n):
|
| 436 |
+
return False
|
| 437 |
+
|
| 438 |
+
D, P, Q = _lucas_extrastrong_params(n)
|
| 439 |
+
if D == 0:
|
| 440 |
+
return False
|
| 441 |
+
|
| 442 |
+
# remove powers of 2 from n+1 (= k * 2**s)
|
| 443 |
+
s = bit_scan1(n + 1)
|
| 444 |
+
k = (n + 1) >> s
|
| 445 |
+
|
| 446 |
+
U, V, _ = _lucas_sequence(n, P, Q, k)
|
| 447 |
+
|
| 448 |
+
if U == 0 and (V == 2 or V == n - 2):
|
| 449 |
+
return True
|
| 450 |
+
for _ in range(1, s):
|
| 451 |
+
if V == 0:
|
| 452 |
+
return True
|
| 453 |
+
V = (V*V - 2) % n
|
| 454 |
+
return False
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def proth_test(n):
|
| 458 |
+
r""" Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.
|
| 459 |
+
|
| 460 |
+
Parameters
|
| 461 |
+
==========
|
| 462 |
+
|
| 463 |
+
n : Integer
|
| 464 |
+
``n`` is Proth number
|
| 465 |
+
|
| 466 |
+
Returns
|
| 467 |
+
=======
|
| 468 |
+
|
| 469 |
+
bool : If ``True``, then ``n`` is the Proth prime
|
| 470 |
+
|
| 471 |
+
Raises
|
| 472 |
+
======
|
| 473 |
+
|
| 474 |
+
ValueError
|
| 475 |
+
If ``n`` is not Proth number.
|
| 476 |
+
|
| 477 |
+
Examples
|
| 478 |
+
========
|
| 479 |
+
|
| 480 |
+
>>> from sympy.ntheory.primetest import proth_test
|
| 481 |
+
>>> proth_test(41)
|
| 482 |
+
True
|
| 483 |
+
>>> proth_test(57)
|
| 484 |
+
False
|
| 485 |
+
|
| 486 |
+
References
|
| 487 |
+
==========
|
| 488 |
+
|
| 489 |
+
.. [1] https://en.wikipedia.org/wiki/Proth_prime
|
| 490 |
+
|
| 491 |
+
"""
|
| 492 |
+
n = as_int(n)
|
| 493 |
+
if n < 3:
|
| 494 |
+
raise ValueError("n is not Proth number")
|
| 495 |
+
m = bit_scan1(n - 1)
|
| 496 |
+
k = n >> m
|
| 497 |
+
if m < k.bit_length():
|
| 498 |
+
raise ValueError("n is not Proth number")
|
| 499 |
+
if n % 3 == 0:
|
| 500 |
+
return n == 3
|
| 501 |
+
if k % 3: # n % 12 == 5
|
| 502 |
+
return pow(3, n >> 1, n) == n - 1
|
| 503 |
+
# If `n` is a square number, then `jacobi(a, n) = 1` for any `a`
|
| 504 |
+
if gmpy_is_square(n):
|
| 505 |
+
return False
|
| 506 |
+
# `a` may be chosen at random.
|
| 507 |
+
# In any case, we want to find `a` such that `jacobi(a, n) = -1`.
|
| 508 |
+
for a in range(5, n):
|
| 509 |
+
j = jacobi(a, n)
|
| 510 |
+
if j == -1:
|
| 511 |
+
return pow(a, n >> 1, n) == n - 1
|
| 512 |
+
if j == 0:
|
| 513 |
+
return False
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def _lucas_lehmer_primality_test(p):
|
| 517 |
+
r""" Test if the Mersenne number `M_p = 2^p-1` is prime.
|
| 518 |
+
|
| 519 |
+
Parameters
|
| 520 |
+
==========
|
| 521 |
+
|
| 522 |
+
p : int
|
| 523 |
+
``p`` is an odd prime number
|
| 524 |
+
|
| 525 |
+
Returns
|
| 526 |
+
=======
|
| 527 |
+
|
| 528 |
+
bool : If ``True``, then `M_p` is the Mersenne prime
|
| 529 |
+
|
| 530 |
+
Examples
|
| 531 |
+
========
|
| 532 |
+
|
| 533 |
+
>>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
|
| 534 |
+
>>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
|
| 535 |
+
True
|
| 536 |
+
>>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
|
| 537 |
+
False
|
| 538 |
+
|
| 539 |
+
See Also
|
| 540 |
+
========
|
| 541 |
+
|
| 542 |
+
is_mersenne_prime
|
| 543 |
+
|
| 544 |
+
References
|
| 545 |
+
==========
|
| 546 |
+
|
| 547 |
+
.. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
|
| 548 |
+
|
| 549 |
+
"""
|
| 550 |
+
v = 4
|
| 551 |
+
m = 2**p - 1
|
| 552 |
+
for _ in range(p - 2):
|
| 553 |
+
v = pow(v, 2, m) - 2
|
| 554 |
+
return v == 0
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def is_mersenne_prime(n):
|
| 558 |
+
"""Returns True if ``n`` is a Mersenne prime, else False.
|
| 559 |
+
|
| 560 |
+
A Mersenne prime is a prime number having the form `2^i - 1`.
|
| 561 |
+
|
| 562 |
+
Examples
|
| 563 |
+
========
|
| 564 |
+
|
| 565 |
+
>>> from sympy.ntheory.factor_ import is_mersenne_prime
|
| 566 |
+
>>> is_mersenne_prime(6)
|
| 567 |
+
False
|
| 568 |
+
>>> is_mersenne_prime(127)
|
| 569 |
+
True
|
| 570 |
+
|
| 571 |
+
References
|
| 572 |
+
==========
|
| 573 |
+
|
| 574 |
+
.. [1] https://mathworld.wolfram.com/MersennePrime.html
|
| 575 |
+
|
| 576 |
+
"""
|
| 577 |
+
n = as_int(n)
|
| 578 |
+
if n < 1:
|
| 579 |
+
return False
|
| 580 |
+
if n & (n + 1):
|
| 581 |
+
# n is not Mersenne number
|
| 582 |
+
return False
|
| 583 |
+
p = n.bit_length()
|
| 584 |
+
if p in MERSENNE_PRIME_EXPONENTS:
|
| 585 |
+
return True
|
| 586 |
+
if p < 65_000_000 or not isprime(p):
|
| 587 |
+
# According to GIMPS, verification was completed on September 19, 2023 for p less than 65 million.
|
| 588 |
+
# https://www.mersenne.org/report_milestones/
|
| 589 |
+
# If p is composite number, then n=2**p-1 is composite number.
|
| 590 |
+
return False
|
| 591 |
+
result = _lucas_lehmer_primality_test(p)
|
| 592 |
+
if result:
|
| 593 |
+
raise ValueError(filldedent('''
|
| 594 |
+
This Mersenne Prime, 2^%s - 1, should
|
| 595 |
+
be added to SymPy's known values.''' % p))
|
| 596 |
+
return result
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def isprime(n):
|
| 600 |
+
"""
|
| 601 |
+
Test if n is a prime number (True) or not (False). For n < 2^64 the
|
| 602 |
+
answer is definitive; larger n values have a small probability of actually
|
| 603 |
+
being pseudoprimes.
|
| 604 |
+
|
| 605 |
+
Negative numbers (e.g. -2) are not considered prime.
|
| 606 |
+
|
| 607 |
+
The first step is looking for trivial factors, which if found enables
|
| 608 |
+
a quick return. Next, if the sieve is large enough, use bisection search
|
| 609 |
+
on the sieve. For small numbers, a set of deterministic Miller-Rabin
|
| 610 |
+
tests are performed with bases that are known to have no counterexamples
|
| 611 |
+
in their range. Finally if the number is larger than 2^64, a strong
|
| 612 |
+
BPSW test is performed. While this is a probable prime test and we
|
| 613 |
+
believe counterexamples exist, there are no known counterexamples.
|
| 614 |
+
|
| 615 |
+
Examples
|
| 616 |
+
========
|
| 617 |
+
|
| 618 |
+
>>> from sympy.ntheory import isprime
|
| 619 |
+
>>> isprime(13)
|
| 620 |
+
True
|
| 621 |
+
>>> isprime(15)
|
| 622 |
+
False
|
| 623 |
+
|
| 624 |
+
Notes
|
| 625 |
+
=====
|
| 626 |
+
|
| 627 |
+
This routine is intended only for integer input, not numerical
|
| 628 |
+
expressions which may represent numbers. Floats are also
|
| 629 |
+
rejected as input because they represent numbers of limited
|
| 630 |
+
precision. While it is tempting to permit 7.0 to represent an
|
| 631 |
+
integer there are errors that may "pass silently" if this is
|
| 632 |
+
allowed:
|
| 633 |
+
|
| 634 |
+
>>> from sympy import Float, S
|
| 635 |
+
>>> int(1e3) == 1e3 == 10**3
|
| 636 |
+
True
|
| 637 |
+
>>> int(1e23) == 1e23
|
| 638 |
+
True
|
| 639 |
+
>>> int(1e23) == 10**23
|
| 640 |
+
False
|
| 641 |
+
|
| 642 |
+
>>> near_int = 1 + S(1)/10**19
|
| 643 |
+
>>> near_int == int(near_int)
|
| 644 |
+
False
|
| 645 |
+
>>> n = Float(near_int, 10) # truncated by precision
|
| 646 |
+
>>> n % 1 == 0
|
| 647 |
+
True
|
| 648 |
+
>>> n = Float(near_int, 20)
|
| 649 |
+
>>> n % 1 == 0
|
| 650 |
+
False
|
| 651 |
+
|
| 652 |
+
See Also
|
| 653 |
+
========
|
| 654 |
+
|
| 655 |
+
sympy.ntheory.generate.primerange : Generates all primes in a given range
|
| 656 |
+
sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
|
| 657 |
+
sympy.ntheory.generate.prime : Return the nth prime
|
| 658 |
+
|
| 659 |
+
References
|
| 660 |
+
==========
|
| 661 |
+
.. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
|
| 662 |
+
.. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
|
| 663 |
+
Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
|
| 664 |
+
https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
|
| 665 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
| 666 |
+
.. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
|
| 667 |
+
"""
|
| 668 |
+
n = as_int(n)
|
| 669 |
+
|
| 670 |
+
# Step 1, do quick composite testing via trial division. The individual
|
| 671 |
+
# modulo tests benchmark faster than one or two primorial igcds for me.
|
| 672 |
+
# The point here is just to speedily handle small numbers and many
|
| 673 |
+
# composites. Step 2 only requires that n <= 2 get handled here.
|
| 674 |
+
if n in [2, 3, 5]:
|
| 675 |
+
return True
|
| 676 |
+
if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
|
| 677 |
+
return False
|
| 678 |
+
if n < 49:
|
| 679 |
+
return True
|
| 680 |
+
if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
|
| 681 |
+
(n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
|
| 682 |
+
(n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
|
| 683 |
+
return False
|
| 684 |
+
if n < 2809:
|
| 685 |
+
return True
|
| 686 |
+
if n < 65077:
|
| 687 |
+
# There are only five Euler pseudoprimes with a least prime factor greater than 47
|
| 688 |
+
return pow(2, n >> 1, n) in [1, n - 1] and n not in [8321, 31621, 42799, 49141, 49981]
|
| 689 |
+
|
| 690 |
+
# bisection search on the sieve if the sieve is large enough
|
| 691 |
+
from sympy.ntheory.generate import sieve as s
|
| 692 |
+
if n <= s._list[-1]:
|
| 693 |
+
l, u = s.search(n)
|
| 694 |
+
return l == u
|
| 695 |
+
|
| 696 |
+
# If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
|
| 697 |
+
# This should be a bit faster than our step 2, and for large values will
|
| 698 |
+
# be a lot faster than our step 3 (C+GMP vs. Python).
|
| 699 |
+
if _gmpy is not None:
|
| 700 |
+
return is_strong_bpsw_prp(n)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
# Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
|
| 704 |
+
# https://miller-rabin.appspot.com/
|
| 705 |
+
# for lists. We have made sure the M-R routine will successfully handle
|
| 706 |
+
# bases larger than n, so we can use the minimal set.
|
| 707 |
+
# In September 2015 deterministic numbers were extended to over 2^81.
|
| 708 |
+
# https://arxiv.org/pdf/1509.00864.pdf
|
| 709 |
+
# https://oeis.org/A014233
|
| 710 |
+
if n < 341531:
|
| 711 |
+
return mr(n, [9345883071009581737])
|
| 712 |
+
if n < 885594169:
|
| 713 |
+
return mr(n, [725270293939359937, 3569819667048198375])
|
| 714 |
+
if n < 350269456337:
|
| 715 |
+
return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
|
| 716 |
+
if n < 55245642489451:
|
| 717 |
+
return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
|
| 718 |
+
if n < 7999252175582851:
|
| 719 |
+
return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
|
| 720 |
+
if n < 585226005592931977:
|
| 721 |
+
return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
|
| 722 |
+
if n < 18446744073709551616:
|
| 723 |
+
return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
|
| 724 |
+
if n < 318665857834031151167461:
|
| 725 |
+
return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
|
| 726 |
+
if n < 3317044064679887385961981:
|
| 727 |
+
return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
|
| 728 |
+
|
| 729 |
+
# We could do this instead at any point:
|
| 730 |
+
#if n < 18446744073709551616:
|
| 731 |
+
# return mr(n, [2]) and is_extra_strong_lucas_prp(n)
|
| 732 |
+
|
| 733 |
+
# Here are tests that are safe for MR routines that don't understand
|
| 734 |
+
# large bases.
|
| 735 |
+
#if n < 9080191:
|
| 736 |
+
# return mr(n, [31, 73])
|
| 737 |
+
#if n < 19471033:
|
| 738 |
+
# return mr(n, [2, 299417])
|
| 739 |
+
#if n < 38010307:
|
| 740 |
+
# return mr(n, [2, 9332593])
|
| 741 |
+
#if n < 316349281:
|
| 742 |
+
# return mr(n, [11000544, 31481107])
|
| 743 |
+
#if n < 4759123141:
|
| 744 |
+
# return mr(n, [2, 7, 61])
|
| 745 |
+
#if n < 105936894253:
|
| 746 |
+
# return mr(n, [2, 1005905886, 1340600841])
|
| 747 |
+
#if n < 31858317218647:
|
| 748 |
+
# return mr(n, [2, 642735, 553174392, 3046413974])
|
| 749 |
+
#if n < 3071837692357849:
|
| 750 |
+
# return mr(n, [2, 75088, 642735, 203659041, 3613982119])
|
| 751 |
+
#if n < 18446744073709551616:
|
| 752 |
+
# return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
|
| 753 |
+
|
| 754 |
+
# Step 3: BPSW.
|
| 755 |
+
#
|
| 756 |
+
# Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
|
| 757 |
+
# 44.0s old isprime using 46 bases
|
| 758 |
+
# 5.3s strong BPSW + one random base
|
| 759 |
+
# 4.3s extra strong BPSW + one random base
|
| 760 |
+
# 4.1s strong BPSW
|
| 761 |
+
# 3.2s extra strong BPSW
|
| 762 |
+
|
| 763 |
+
# Classic BPSW from page 1401 of the paper. See alternate ideas below.
|
| 764 |
+
return is_strong_bpsw_prp(n)
|
| 765 |
+
|
| 766 |
+
# Using extra strong test, which is somewhat faster
|
| 767 |
+
#return mr(n, [2]) and is_extra_strong_lucas_prp(n)
|
| 768 |
+
|
| 769 |
+
# Add a random M-R base
|
| 770 |
+
#import random
|
| 771 |
+
#return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def is_gaussian_prime(num):
|
| 775 |
+
r"""Test if num is a Gaussian prime number.
|
| 776 |
+
|
| 777 |
+
References
|
| 778 |
+
==========
|
| 779 |
+
|
| 780 |
+
.. [1] https://oeis.org/wiki/Gaussian_primes
|
| 781 |
+
"""
|
| 782 |
+
|
| 783 |
+
num = sympify(num)
|
| 784 |
+
a, b = num.as_real_imag()
|
| 785 |
+
a = as_int(a, strict=False)
|
| 786 |
+
b = as_int(b, strict=False)
|
| 787 |
+
if a == 0:
|
| 788 |
+
b = abs(b)
|
| 789 |
+
return isprime(b) and b % 4 == 3
|
| 790 |
+
elif b == 0:
|
| 791 |
+
a = abs(a)
|
| 792 |
+
return isprime(a) and a % 4 == 3
|
| 793 |
+
return isprime(a**2 + b**2)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/qs.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.random import _randint
|
| 2 |
+
from sympy.external.gmpy import gcd, invert, sqrt as isqrt
|
| 3 |
+
from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
|
| 4 |
+
from sympy.ntheory import isprime
|
| 5 |
+
from math import log, sqrt
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SievePolynomial:
|
| 9 |
+
def __init__(self, modified_coeff=(), a=None, b=None):
|
| 10 |
+
"""This class denotes the seive polynomial.
|
| 11 |
+
If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded
|
| 12 |
+
to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient
|
| 13 |
+
is stored in the form `[a**2, 2*a*b, b**2 - N]`. This
|
| 14 |
+
ensures faster `eval` method because we dont have to
|
| 15 |
+
perform `a**2, 2*a*b, b**2` every time we call the
|
| 16 |
+
`eval` method. As multiplication is more expensive
|
| 17 |
+
than addition, by using modified_coefficient we get
|
| 18 |
+
a faster seiving process.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
==========
|
| 22 |
+
|
| 23 |
+
modified_coeff : modified_coefficient of sieve polynomial
|
| 24 |
+
a : parameter of the sieve polynomial
|
| 25 |
+
b : parameter of the sieve polynomial
|
| 26 |
+
"""
|
| 27 |
+
self.modified_coeff = modified_coeff
|
| 28 |
+
self.a = a
|
| 29 |
+
self.b = b
|
| 30 |
+
|
| 31 |
+
def eval(self, x):
|
| 32 |
+
"""
|
| 33 |
+
Compute the value of the sieve polynomial at point x.
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
==========
|
| 37 |
+
|
| 38 |
+
x : Integer parameter for sieve polynomial
|
| 39 |
+
"""
|
| 40 |
+
ans = 0
|
| 41 |
+
for coeff in self.modified_coeff:
|
| 42 |
+
ans *= x
|
| 43 |
+
ans += coeff
|
| 44 |
+
return ans
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class FactorBaseElem:
|
| 48 |
+
"""This class stores an element of the `factor_base`.
|
| 49 |
+
"""
|
| 50 |
+
def __init__(self, prime, tmem_p, log_p):
|
| 51 |
+
"""
|
| 52 |
+
Initialization of factor_base_elem.
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
==========
|
| 56 |
+
|
| 57 |
+
prime : prime number of the factor_base
|
| 58 |
+
tmem_p : Integer square root of x**2 = n mod prime
|
| 59 |
+
log_p : Compute Natural Logarithm of the prime
|
| 60 |
+
"""
|
| 61 |
+
self.prime = prime
|
| 62 |
+
self.tmem_p = tmem_p
|
| 63 |
+
self.log_p = log_p
|
| 64 |
+
self.soln1 = None
|
| 65 |
+
self.soln2 = None
|
| 66 |
+
self.a_inv = None
|
| 67 |
+
self.b_ainv = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _generate_factor_base(prime_bound, n):
|
| 71 |
+
"""Generate `factor_base` for Quadratic Sieve. The `factor_base`
|
| 72 |
+
consists of all the points whose ``legendre_symbol(n, p) == 1``
|
| 73 |
+
and ``p < num_primes``. Along with the prime `factor_base` also stores
|
| 74 |
+
natural logarithm of prime and the residue n modulo p.
|
| 75 |
+
It also returns the of primes numbers in the `factor_base` which are
|
| 76 |
+
close to 1000 and 5000.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
==========
|
| 80 |
+
|
| 81 |
+
prime_bound : upper prime bound of the factor_base
|
| 82 |
+
n : integer to be factored
|
| 83 |
+
"""
|
| 84 |
+
from sympy.ntheory.generate import sieve
|
| 85 |
+
factor_base = []
|
| 86 |
+
idx_1000, idx_5000 = None, None
|
| 87 |
+
for prime in sieve.primerange(1, prime_bound):
|
| 88 |
+
if pow(n, (prime - 1) // 2, prime) == 1:
|
| 89 |
+
if prime > 1000 and idx_1000 is None:
|
| 90 |
+
idx_1000 = len(factor_base) - 1
|
| 91 |
+
if prime > 5000 and idx_5000 is None:
|
| 92 |
+
idx_5000 = len(factor_base) - 1
|
| 93 |
+
residue = _sqrt_mod_prime_power(n, prime, 1)[0]
|
| 94 |
+
log_p = round(log(prime)*2**10)
|
| 95 |
+
factor_base.append(FactorBaseElem(prime, residue, log_p))
|
| 96 |
+
return idx_1000, idx_5000, factor_base
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None):
|
| 100 |
+
"""This step is the initialization of the 1st sieve polynomial.
|
| 101 |
+
Here `a` is selected as a product of several primes of the factor_base
|
| 102 |
+
such that `a` is about to ``sqrt(2*N) / M``. Other initial values of
|
| 103 |
+
factor_base elem are also initialized which includes a_inv, b_ainv, soln1,
|
| 104 |
+
soln2 which are used when the sieve polynomial is changed. The b_ainv
|
| 105 |
+
is required for fast polynomial change as we do not have to calculate
|
| 106 |
+
`2*b*invert(a, prime)` every time.
|
| 107 |
+
We also ensure that the `factor_base` primes which make `a` are between
|
| 108 |
+
1000 and 5000.
|
| 109 |
+
|
| 110 |
+
Parameters
|
| 111 |
+
==========
|
| 112 |
+
|
| 113 |
+
N : Number to be factored
|
| 114 |
+
M : sieve interval
|
| 115 |
+
factor_base : factor_base primes
|
| 116 |
+
idx_1000 : index of prime number in the factor_base near 1000
|
| 117 |
+
idx_5000 : index of prime number in the factor_base near to 5000
|
| 118 |
+
seed : Generate pseudoprime numbers
|
| 119 |
+
"""
|
| 120 |
+
randint = _randint(seed)
|
| 121 |
+
approx_val = sqrt(2*N) / M
|
| 122 |
+
# `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a`
|
| 123 |
+
# randomly search for a combination of primes whose multiplication is close to approx_val
|
| 124 |
+
# This multiplication of primes will be `a` and the primes will be `q`
|
| 125 |
+
# `best_a` denotes that `a` is close to approx_val in the random search of combination
|
| 126 |
+
best_a, best_q, best_ratio = None, None, None
|
| 127 |
+
start = 0 if idx_1000 is None else idx_1000
|
| 128 |
+
end = len(factor_base) - 1 if idx_5000 is None else idx_5000
|
| 129 |
+
for _ in range(50):
|
| 130 |
+
a = 1
|
| 131 |
+
q = []
|
| 132 |
+
while(a < approx_val):
|
| 133 |
+
rand_p = 0
|
| 134 |
+
while(rand_p == 0 or rand_p in q):
|
| 135 |
+
rand_p = randint(start, end)
|
| 136 |
+
p = factor_base[rand_p].prime
|
| 137 |
+
a *= p
|
| 138 |
+
q.append(rand_p)
|
| 139 |
+
ratio = a / approx_val
|
| 140 |
+
if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
|
| 141 |
+
best_q = q
|
| 142 |
+
best_a = a
|
| 143 |
+
best_ratio = ratio
|
| 144 |
+
|
| 145 |
+
a = best_a
|
| 146 |
+
q = best_q
|
| 147 |
+
|
| 148 |
+
B = []
|
| 149 |
+
for val in q:
|
| 150 |
+
q_l = factor_base[val].prime
|
| 151 |
+
gamma = factor_base[val].tmem_p * invert(a // q_l, q_l) % q_l
|
| 152 |
+
if gamma > q_l / 2:
|
| 153 |
+
gamma = q_l - gamma
|
| 154 |
+
B.append(a//q_l*gamma)
|
| 155 |
+
|
| 156 |
+
b = sum(B)
|
| 157 |
+
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
|
| 158 |
+
|
| 159 |
+
for fb in factor_base:
|
| 160 |
+
if a % fb.prime == 0:
|
| 161 |
+
continue
|
| 162 |
+
fb.a_inv = invert(a, fb.prime)
|
| 163 |
+
fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B]
|
| 164 |
+
fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime
|
| 165 |
+
fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime
|
| 166 |
+
return g, B
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _initialize_ith_poly(N, factor_base, i, g, B):
|
| 170 |
+
"""Initialization stage of ith poly. After we finish sieving 1`st polynomial
|
| 171 |
+
here we quickly change to the next polynomial from which we will again
|
| 172 |
+
start sieving. Suppose we generated ith sieve polynomial and now we
|
| 173 |
+
want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1``
|
| 174 |
+
where `j` is the number of prime factors of the coefficient `a`
|
| 175 |
+
then this function can be used to go to the next polynomial. If
|
| 176 |
+
``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage.
|
| 177 |
+
|
| 178 |
+
Parameters
|
| 179 |
+
==========
|
| 180 |
+
|
| 181 |
+
N : number to be factored
|
| 182 |
+
factor_base : factor_base primes
|
| 183 |
+
i : integer denoting ith polynomial
|
| 184 |
+
g : (i - 1)th polynomial
|
| 185 |
+
B : array that stores a//q_l*gamma
|
| 186 |
+
"""
|
| 187 |
+
from sympy.functions.elementary.integers import ceiling
|
| 188 |
+
v = 1
|
| 189 |
+
j = i
|
| 190 |
+
while(j % 2 == 0):
|
| 191 |
+
v += 1
|
| 192 |
+
j //= 2
|
| 193 |
+
if ceiling(i / (2**v)) % 2 == 1:
|
| 194 |
+
neg_pow = -1
|
| 195 |
+
else:
|
| 196 |
+
neg_pow = 1
|
| 197 |
+
b = g.b + 2*neg_pow*B[v - 1]
|
| 198 |
+
a = g.a
|
| 199 |
+
g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b)
|
| 200 |
+
for fb in factor_base:
|
| 201 |
+
if a % fb.prime == 0:
|
| 202 |
+
continue
|
| 203 |
+
fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
|
| 204 |
+
fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime
|
| 205 |
+
|
| 206 |
+
return g
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _gen_sieve_array(M, factor_base):
|
| 210 |
+
"""Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
|
| 211 |
+
that does not divide the coefficient `a` we add log_p over the sieve_array
|
| 212 |
+
such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
|
| 213 |
+
is an integer. When p = 2 then log_p is only added using
|
| 214 |
+
``-M <= soln1 + i*p <= M``.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
==========
|
| 218 |
+
|
| 219 |
+
M : sieve interval
|
| 220 |
+
factor_base : factor_base primes
|
| 221 |
+
"""
|
| 222 |
+
sieve_array = [0]*(2*M + 1)
|
| 223 |
+
for factor in factor_base:
|
| 224 |
+
if factor.soln1 is None: #The prime does not divides a
|
| 225 |
+
continue
|
| 226 |
+
for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
|
| 227 |
+
sieve_array[idx] += factor.log_p
|
| 228 |
+
if factor.prime == 2:
|
| 229 |
+
continue
|
| 230 |
+
#if prime is 2 then sieve only with soln_1_p
|
| 231 |
+
for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
|
| 232 |
+
sieve_array[idx] += factor.log_p
|
| 233 |
+
return sieve_array
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _check_smoothness(num, factor_base):
|
| 237 |
+
"""Here we check that if `num` is a smooth number or not. If `a` is a smooth
|
| 238 |
+
number then it returns a vector of prime exponents modulo 2. For example
|
| 239 |
+
if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then
|
| 240 |
+
`a` is a smooth number and this function returns ([1, 0, 0, 1], True). If
|
| 241 |
+
`a` is a partial relation which means that `a` a has one prime factor
|
| 242 |
+
greater than the `factor_base` then it returns `(a, False)` which denotes `a`
|
| 243 |
+
is a partial relation.
|
| 244 |
+
|
| 245 |
+
Parameters
|
| 246 |
+
==========
|
| 247 |
+
|
| 248 |
+
a : integer whose smootheness is to be checked
|
| 249 |
+
factor_base : factor_base primes
|
| 250 |
+
"""
|
| 251 |
+
vec = []
|
| 252 |
+
if num < 0:
|
| 253 |
+
vec.append(1)
|
| 254 |
+
num *= -1
|
| 255 |
+
else:
|
| 256 |
+
vec.append(0)
|
| 257 |
+
#-1 is not included in factor_base add -1 in vector
|
| 258 |
+
for factor in factor_base:
|
| 259 |
+
if num % factor.prime != 0:
|
| 260 |
+
vec.append(0)
|
| 261 |
+
continue
|
| 262 |
+
factor_exp = 0
|
| 263 |
+
while num % factor.prime == 0:
|
| 264 |
+
factor_exp += 1
|
| 265 |
+
num //= factor.prime
|
| 266 |
+
vec.append(factor_exp % 2)
|
| 267 |
+
if num == 1:
|
| 268 |
+
return vec, True
|
| 269 |
+
if isprime(num):
|
| 270 |
+
return num, False
|
| 271 |
+
return None, None
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
|
| 275 |
+
"""Trial division stage. Here we trial divide the values generetated
|
| 276 |
+
by sieve_poly in the sieve interval and if it is a smooth number then
|
| 277 |
+
it is stored in `smooth_relations`. Moreover, if we find two partial relations
|
| 278 |
+
with same large prime then they are combined to form a smooth relation.
|
| 279 |
+
First we iterate over sieve array and look for values which are greater
|
| 280 |
+
than accumulated_val, as these values have a high chance of being smooth
|
| 281 |
+
number. Then using these values we find smooth relations.
|
| 282 |
+
In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
|
| 283 |
+
with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
|
| 284 |
+
to form a smooth relation.
|
| 285 |
+
|
| 286 |
+
Parameters
|
| 287 |
+
==========
|
| 288 |
+
|
| 289 |
+
N : Number to be factored
|
| 290 |
+
M : sieve interval
|
| 291 |
+
factor_base : factor_base primes
|
| 292 |
+
sieve_array : stores log_p values
|
| 293 |
+
sieve_poly : polynomial from which we find smooth relations
|
| 294 |
+
partial_relations : stores partial relations with one large prime
|
| 295 |
+
ERROR_TERM : error term for accumulated_val
|
| 296 |
+
"""
|
| 297 |
+
sqrt_n = isqrt(N)
|
| 298 |
+
accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM
|
| 299 |
+
smooth_relations = []
|
| 300 |
+
proper_factor = set()
|
| 301 |
+
partial_relation_upper_bound = 128*factor_base[-1].prime
|
| 302 |
+
for idx, val in enumerate(sieve_array):
|
| 303 |
+
if val < accumulated_val:
|
| 304 |
+
continue
|
| 305 |
+
x = idx - M
|
| 306 |
+
v = sieve_poly.eval(x)
|
| 307 |
+
vec, is_smooth = _check_smoothness(v, factor_base)
|
| 308 |
+
if is_smooth is None:#Neither smooth nor partial
|
| 309 |
+
continue
|
| 310 |
+
u = sieve_poly.a*x + sieve_poly.b
|
| 311 |
+
# Update the partial relation
|
| 312 |
+
# If 2 partial relation with same large prime is found then generate smooth relation
|
| 313 |
+
if is_smooth is False:#partial relation found
|
| 314 |
+
large_prime = vec
|
| 315 |
+
#Consider the large_primes under 128*F
|
| 316 |
+
if large_prime > partial_relation_upper_bound:
|
| 317 |
+
continue
|
| 318 |
+
if large_prime not in partial_relations:
|
| 319 |
+
partial_relations[large_prime] = (u, v)
|
| 320 |
+
continue
|
| 321 |
+
else:
|
| 322 |
+
u_prev, v_prev = partial_relations[large_prime]
|
| 323 |
+
partial_relations.pop(large_prime)
|
| 324 |
+
try:
|
| 325 |
+
large_prime_inv = invert(large_prime, N)
|
| 326 |
+
except ZeroDivisionError:#if large_prime divides N
|
| 327 |
+
proper_factor.add(large_prime)
|
| 328 |
+
continue
|
| 329 |
+
u = u*u_prev*large_prime_inv
|
| 330 |
+
v = v*v_prev // (large_prime*large_prime)
|
| 331 |
+
vec, is_smooth = _check_smoothness(v, factor_base)
|
| 332 |
+
#assert u*u % N == v % N
|
| 333 |
+
smooth_relations.append((u, v, vec))
|
| 334 |
+
return smooth_relations, proper_factor
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
#LINEAR ALGEBRA STAGE
|
| 338 |
+
def _build_matrix(smooth_relations):
|
| 339 |
+
"""Build a 2D matrix from smooth relations.
|
| 340 |
+
|
| 341 |
+
Parameters
|
| 342 |
+
==========
|
| 343 |
+
|
| 344 |
+
smooth_relations : Stores smooth relations
|
| 345 |
+
"""
|
| 346 |
+
matrix = []
|
| 347 |
+
for s_relation in smooth_relations:
|
| 348 |
+
matrix.append(s_relation[2])
|
| 349 |
+
return matrix
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _gauss_mod_2(A):
|
| 353 |
+
"""Fast gaussian reduction for modulo 2 matrix.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
==========
|
| 357 |
+
|
| 358 |
+
A : Matrix
|
| 359 |
+
|
| 360 |
+
Examples
|
| 361 |
+
========
|
| 362 |
+
|
| 363 |
+
>>> from sympy.ntheory.qs import _gauss_mod_2
|
| 364 |
+
>>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]])
|
| 365 |
+
([[[1, 0, 1], 3]],
|
| 366 |
+
[True, True, True, False],
|
| 367 |
+
[[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]])
|
| 368 |
+
|
| 369 |
+
Reference
|
| 370 |
+
==========
|
| 371 |
+
|
| 372 |
+
.. [1] A fast algorithm for gaussian elimination over GF(2) and
|
| 373 |
+
its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige"""
|
| 374 |
+
import copy
|
| 375 |
+
matrix = copy.deepcopy(A)
|
| 376 |
+
row = len(matrix)
|
| 377 |
+
col = len(matrix[0])
|
| 378 |
+
mark = [False]*row
|
| 379 |
+
for c in range(col):
|
| 380 |
+
for r in range(row):
|
| 381 |
+
if matrix[r][c] == 1:
|
| 382 |
+
break
|
| 383 |
+
mark[r] = True
|
| 384 |
+
for c1 in range(col):
|
| 385 |
+
if c1 == c:
|
| 386 |
+
continue
|
| 387 |
+
if matrix[r][c1] == 1:
|
| 388 |
+
for r2 in range(row):
|
| 389 |
+
matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2
|
| 390 |
+
dependent_row = []
|
| 391 |
+
for idx, val in enumerate(mark):
|
| 392 |
+
if val == False:
|
| 393 |
+
dependent_row.append([matrix[idx], idx])
|
| 394 |
+
return dependent_row, mark, matrix
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N):
|
| 398 |
+
"""Finds proper factor of N. Here, transform the dependent rows as a
|
| 399 |
+
combination of independent rows of the gauss_matrix to form the desired
|
| 400 |
+
relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation
|
| 401 |
+
we obtain a proper factor of N by `gcd(X - Y, N)`.
|
| 402 |
+
|
| 403 |
+
Parameters
|
| 404 |
+
==========
|
| 405 |
+
|
| 406 |
+
dependent_rows : denoted dependent rows in the reduced matrix form
|
| 407 |
+
mark : boolean array to denoted dependent and independent rows
|
| 408 |
+
gauss_matrix : Reduced form of the smooth relations matrix
|
| 409 |
+
index : denoted the index of the dependent_rows
|
| 410 |
+
smooth_relations : Smooth relations vectors matrix
|
| 411 |
+
N : Number to be factored
|
| 412 |
+
"""
|
| 413 |
+
idx_in_smooth = dependent_rows[index][1]
|
| 414 |
+
independent_u = [smooth_relations[idx_in_smooth][0]]
|
| 415 |
+
independent_v = [smooth_relations[idx_in_smooth][1]]
|
| 416 |
+
dept_row = dependent_rows[index][0]
|
| 417 |
+
|
| 418 |
+
for idx, val in enumerate(dept_row):
|
| 419 |
+
if val == 1:
|
| 420 |
+
for row in range(len(gauss_matrix)):
|
| 421 |
+
if gauss_matrix[row][idx] == 1 and mark[row] == True:
|
| 422 |
+
independent_u.append(smooth_relations[row][0])
|
| 423 |
+
independent_v.append(smooth_relations[row][1])
|
| 424 |
+
break
|
| 425 |
+
|
| 426 |
+
u = 1
|
| 427 |
+
v = 1
|
| 428 |
+
for i in independent_u:
|
| 429 |
+
u *= i
|
| 430 |
+
for i in independent_v:
|
| 431 |
+
v *= i
|
| 432 |
+
#assert u**2 % N == v % N
|
| 433 |
+
v = isqrt(v)
|
| 434 |
+
return gcd(u - v, N)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
|
| 438 |
+
"""Performs factorization using Self-Initializing Quadratic Sieve.
|
| 439 |
+
In SIQS, let N be a number to be factored, and this N should not be a
|
| 440 |
+
perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
|
| 441 |
+
``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
|
| 442 |
+
In order to find these integers X and Y we try to find relations of form
|
| 443 |
+
t**2 = u modN where u is a product of small primes. If we have enough of
|
| 444 |
+
these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
|
| 445 |
+
the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
|
| 446 |
+
|
| 447 |
+
Here, several optimizations are done like using multiple polynomials for
|
| 448 |
+
sieving, fast changing between polynomials and using partial relations.
|
| 449 |
+
The use of partial relations can speeds up the factoring by 2 times.
|
| 450 |
+
|
| 451 |
+
Parameters
|
| 452 |
+
==========
|
| 453 |
+
|
| 454 |
+
N : Number to be Factored
|
| 455 |
+
prime_bound : upper bound for primes in the factor base
|
| 456 |
+
M : Sieve Interval
|
| 457 |
+
ERROR_TERM : Error term for checking smoothness
|
| 458 |
+
threshold : Extra smooth relations for factorization
|
| 459 |
+
seed : generate pseudo prime numbers
|
| 460 |
+
|
| 461 |
+
Examples
|
| 462 |
+
========
|
| 463 |
+
|
| 464 |
+
>>> from sympy.ntheory import qs
|
| 465 |
+
>>> qs(25645121643901801, 2000, 10000)
|
| 466 |
+
{5394769, 4753701529}
|
| 467 |
+
>>> qs(9804659461513846513, 2000, 10000)
|
| 468 |
+
{4641991, 2112166839943}
|
| 469 |
+
|
| 470 |
+
References
|
| 471 |
+
==========
|
| 472 |
+
|
| 473 |
+
.. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
|
| 474 |
+
.. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
|
| 475 |
+
"""
|
| 476 |
+
ERROR_TERM*=2**10
|
| 477 |
+
idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
|
| 478 |
+
smooth_relations = []
|
| 479 |
+
ith_poly = 0
|
| 480 |
+
partial_relations = {}
|
| 481 |
+
proper_factor = set()
|
| 482 |
+
threshold = 5*len(factor_base) // 100
|
| 483 |
+
while True:
|
| 484 |
+
if ith_poly == 0:
|
| 485 |
+
ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000)
|
| 486 |
+
else:
|
| 487 |
+
ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array)
|
| 488 |
+
ith_poly += 1
|
| 489 |
+
if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial
|
| 490 |
+
ith_poly = 0
|
| 491 |
+
sieve_array = _gen_sieve_array(M, factor_base)
|
| 492 |
+
s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM)
|
| 493 |
+
smooth_relations += s_rel
|
| 494 |
+
proper_factor |= p_f
|
| 495 |
+
if len(smooth_relations) >= len(factor_base) + threshold:
|
| 496 |
+
break
|
| 497 |
+
matrix = _build_matrix(smooth_relations)
|
| 498 |
+
dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix)
|
| 499 |
+
N_copy = N
|
| 500 |
+
for index in range(len(dependent_row)):
|
| 501 |
+
factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N)
|
| 502 |
+
if factor > 1 and factor < N:
|
| 503 |
+
proper_factor.add(factor)
|
| 504 |
+
while(N_copy % factor == 0):
|
| 505 |
+
N_copy //= factor
|
| 506 |
+
if isprime(N_copy):
|
| 507 |
+
proper_factor.add(N_copy)
|
| 508 |
+
break
|
| 509 |
+
if(N_copy == 1):
|
| 510 |
+
break
|
| 511 |
+
return proper_factor
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/resid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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from sympy.external.gmpy import (gcd, lcm, invert, sqrt, jacobi,
|
| 4 |
+
bit_scan1, remove)
|
| 5 |
+
from sympy.polys import Poly
|
| 6 |
+
from sympy.polys.domains import ZZ
|
| 7 |
+
from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence, gf_csolve
|
| 8 |
+
from .primetest import isprime
|
| 9 |
+
from .generate import primerange
|
| 10 |
+
from .factor_ import factorint, _perfect_power
|
| 11 |
+
from .modular import crt
|
| 12 |
+
from sympy.utilities.decorator import deprecated
|
| 13 |
+
from sympy.utilities.memoization import recurrence_memo
|
| 14 |
+
from sympy.utilities.misc import as_int
|
| 15 |
+
from sympy.utilities.iterables import iproduct
|
| 16 |
+
from sympy.core.random import _randint, randint
|
| 17 |
+
|
| 18 |
+
from itertools import product
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def n_order(a, n):
|
| 22 |
+
r""" Returns the order of ``a`` modulo ``n``.
|
| 23 |
+
|
| 24 |
+
Explanation
|
| 25 |
+
===========
|
| 26 |
+
|
| 27 |
+
The order of ``a`` modulo ``n`` is the smallest integer
|
| 28 |
+
``k`` such that `a^k` leaves a remainder of 1 with ``n``.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
==========
|
| 32 |
+
|
| 33 |
+
a : integer
|
| 34 |
+
n : integer, n > 1. a and n should be relatively prime
|
| 35 |
+
|
| 36 |
+
Returns
|
| 37 |
+
=======
|
| 38 |
+
|
| 39 |
+
int : the order of ``a`` modulo ``n``
|
| 40 |
+
|
| 41 |
+
Raises
|
| 42 |
+
======
|
| 43 |
+
|
| 44 |
+
ValueError
|
| 45 |
+
If `n \le 1` or `\gcd(a, n) \neq 1`.
|
| 46 |
+
If ``a`` or ``n`` is not an integer.
|
| 47 |
+
|
| 48 |
+
Examples
|
| 49 |
+
========
|
| 50 |
+
|
| 51 |
+
>>> from sympy.ntheory import n_order
|
| 52 |
+
>>> n_order(3, 7)
|
| 53 |
+
6
|
| 54 |
+
>>> n_order(4, 7)
|
| 55 |
+
3
|
| 56 |
+
|
| 57 |
+
See Also
|
| 58 |
+
========
|
| 59 |
+
|
| 60 |
+
is_primitive_root
|
| 61 |
+
We say that ``a`` is a primitive root of ``n``
|
| 62 |
+
when the order of ``a`` modulo ``n`` equals ``totient(n)``
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
a, n = as_int(a), as_int(n)
|
| 66 |
+
if n <= 1:
|
| 67 |
+
raise ValueError("n should be an integer greater than 1")
|
| 68 |
+
a = a % n
|
| 69 |
+
# Trivial
|
| 70 |
+
if a == 1:
|
| 71 |
+
return 1
|
| 72 |
+
if gcd(a, n) != 1:
|
| 73 |
+
raise ValueError("The two numbers should be relatively prime")
|
| 74 |
+
a_order = 1
|
| 75 |
+
for p, e in factorint(n).items():
|
| 76 |
+
pe = p**e
|
| 77 |
+
pe_order = (p - 1) * p**(e - 1)
|
| 78 |
+
factors = factorint(p - 1)
|
| 79 |
+
if e > 1:
|
| 80 |
+
factors[p] = e - 1
|
| 81 |
+
order = 1
|
| 82 |
+
for px, ex in factors.items():
|
| 83 |
+
x = pow(a, pe_order // px**ex, pe)
|
| 84 |
+
while x != 1:
|
| 85 |
+
x = pow(x, px, pe)
|
| 86 |
+
order *= px
|
| 87 |
+
a_order = lcm(a_order, order)
|
| 88 |
+
return int(a_order)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _primitive_root_prime_iter(p):
|
| 92 |
+
r""" Generates the primitive roots for a prime ``p``.
|
| 93 |
+
|
| 94 |
+
Explanation
|
| 95 |
+
===========
|
| 96 |
+
|
| 97 |
+
The primitive roots generated are not necessarily sorted.
|
| 98 |
+
However, the first one is the smallest primitive root.
|
| 99 |
+
|
| 100 |
+
Find the element whose order is ``p-1`` from the smaller one.
|
| 101 |
+
If we can find the first primitive root ``g``, we can use the following theorem.
|
| 102 |
+
|
| 103 |
+
.. math ::
|
| 104 |
+
\operatorname{ord}(g^k) = \frac{\operatorname{ord}(g)}{\gcd(\operatorname{ord}(g), k)}
|
| 105 |
+
|
| 106 |
+
From the assumption that `\operatorname{ord}(g)=p-1`,
|
| 107 |
+
it is a necessary and sufficient condition for
|
| 108 |
+
`\operatorname{ord}(g^k)=p-1` that `\gcd(p-1, k)=1`.
|
| 109 |
+
|
| 110 |
+
Parameters
|
| 111 |
+
==========
|
| 112 |
+
|
| 113 |
+
p : odd prime
|
| 114 |
+
|
| 115 |
+
Yields
|
| 116 |
+
======
|
| 117 |
+
|
| 118 |
+
int
|
| 119 |
+
the primitive roots of ``p``
|
| 120 |
+
|
| 121 |
+
Examples
|
| 122 |
+
========
|
| 123 |
+
|
| 124 |
+
>>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
|
| 125 |
+
>>> sorted(_primitive_root_prime_iter(19))
|
| 126 |
+
[2, 3, 10, 13, 14, 15]
|
| 127 |
+
|
| 128 |
+
References
|
| 129 |
+
==========
|
| 130 |
+
|
| 131 |
+
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
|
| 132 |
+
|
| 133 |
+
"""
|
| 134 |
+
if p == 3:
|
| 135 |
+
yield 2
|
| 136 |
+
return
|
| 137 |
+
# Let p = +-1 (mod 4a). Legendre symbol (a/p) = 1, so `a` is not the primitive root.
|
| 138 |
+
# Corollary : If p = +-1 (mod 8), then 2 is not the primitive root of p.
|
| 139 |
+
g_min = 3 if p % 8 in [1, 7] else 2
|
| 140 |
+
if p < 41:
|
| 141 |
+
# small case
|
| 142 |
+
g = 5 if p == 23 else g_min
|
| 143 |
+
else:
|
| 144 |
+
v = [(p - 1) // i for i in factorint(p - 1).keys()]
|
| 145 |
+
for g in range(g_min, p):
|
| 146 |
+
if all(pow(g, pw, p) != 1 for pw in v):
|
| 147 |
+
break
|
| 148 |
+
yield g
|
| 149 |
+
# g**k is the primitive root of p iff gcd(p - 1, k) = 1
|
| 150 |
+
for k in range(3, p, 2):
|
| 151 |
+
if gcd(p - 1, k) == 1:
|
| 152 |
+
yield pow(g, k, p)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _primitive_root_prime_power_iter(p, e):
|
| 156 |
+
r""" Generates the primitive roots of `p^e`.
|
| 157 |
+
|
| 158 |
+
Explanation
|
| 159 |
+
===========
|
| 160 |
+
|
| 161 |
+
Let ``g`` be the primitive root of ``p``.
|
| 162 |
+
If `g^{p-1} \not\equiv 1 \pmod{p^2}`, then ``g`` is primitive root of `p^e`.
|
| 163 |
+
Thus, if we find a primitive root ``g`` of ``p``,
|
| 164 |
+
then `g, g+p, g+2p, \ldots, g+(p-1)p` are primitive roots of `p^2` except one.
|
| 165 |
+
That one satisfies `\hat{g}^{p-1} \equiv 1 \pmod{p^2}`.
|
| 166 |
+
If ``h`` is the primitive root of `p^2`,
|
| 167 |
+
then `h, h+p^2, h+2p^2, \ldots, h+(p^{e-2}-1)p^e` are primitive roots of `p^e`.
|
| 168 |
+
|
| 169 |
+
Parameters
|
| 170 |
+
==========
|
| 171 |
+
|
| 172 |
+
p : odd prime
|
| 173 |
+
e : positive integer
|
| 174 |
+
|
| 175 |
+
Yields
|
| 176 |
+
======
|
| 177 |
+
|
| 178 |
+
int
|
| 179 |
+
the primitive roots of `p^e`
|
| 180 |
+
|
| 181 |
+
Examples
|
| 182 |
+
========
|
| 183 |
+
|
| 184 |
+
>>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power_iter
|
| 185 |
+
>>> sorted(_primitive_root_prime_power_iter(5, 2))
|
| 186 |
+
[2, 3, 8, 12, 13, 17, 22, 23]
|
| 187 |
+
|
| 188 |
+
"""
|
| 189 |
+
if e == 1:
|
| 190 |
+
yield from _primitive_root_prime_iter(p)
|
| 191 |
+
else:
|
| 192 |
+
p2 = p**2
|
| 193 |
+
for g in _primitive_root_prime_iter(p):
|
| 194 |
+
t = (g - pow(g, 2 - p, p2)) % p2
|
| 195 |
+
for k in range(0, p2, p):
|
| 196 |
+
if k != t:
|
| 197 |
+
yield from (g + k + m for m in range(0, p**e, p2))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _primitive_root_prime_power2_iter(p, e):
|
| 201 |
+
r""" Generates the primitive roots of `2p^e`.
|
| 202 |
+
|
| 203 |
+
Explanation
|
| 204 |
+
===========
|
| 205 |
+
|
| 206 |
+
If ``g`` is the primitive root of ``p**e``,
|
| 207 |
+
then the odd one of ``g`` and ``g+p**e`` is the primitive root of ``2*p**e``.
|
| 208 |
+
|
| 209 |
+
Parameters
|
| 210 |
+
==========
|
| 211 |
+
|
| 212 |
+
p : odd prime
|
| 213 |
+
e : positive integer
|
| 214 |
+
|
| 215 |
+
Yields
|
| 216 |
+
======
|
| 217 |
+
|
| 218 |
+
int
|
| 219 |
+
the primitive roots of `2p^e`
|
| 220 |
+
|
| 221 |
+
Examples
|
| 222 |
+
========
|
| 223 |
+
|
| 224 |
+
>>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power2_iter
|
| 225 |
+
>>> sorted(_primitive_root_prime_power2_iter(5, 2))
|
| 226 |
+
[3, 13, 17, 23, 27, 33, 37, 47]
|
| 227 |
+
|
| 228 |
+
"""
|
| 229 |
+
for g in _primitive_root_prime_power_iter(p, e):
|
| 230 |
+
if g % 2 == 1:
|
| 231 |
+
yield g
|
| 232 |
+
else:
|
| 233 |
+
yield g + p**e
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def primitive_root(p, smallest=True):
|
| 237 |
+
r""" Returns a primitive root of ``p`` or None.
|
| 238 |
+
|
| 239 |
+
Explanation
|
| 240 |
+
===========
|
| 241 |
+
|
| 242 |
+
For the definition of primitive root,
|
| 243 |
+
see the explanation of ``is_primitive_root``.
|
| 244 |
+
|
| 245 |
+
The primitive root of ``p`` exist only for
|
| 246 |
+
`p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
|
| 247 |
+
Now, if we know the primitive root of ``q``,
|
| 248 |
+
we can calculate the primitive root of `q^e`,
|
| 249 |
+
and if we know the primitive root of `q^e`,
|
| 250 |
+
we can calculate the primitive root of `2q^e`.
|
| 251 |
+
When there is no need to find the smallest primitive root,
|
| 252 |
+
this property can be used to obtain a fast primitive root.
|
| 253 |
+
On the other hand, when we want the smallest primitive root,
|
| 254 |
+
we naively determine whether it is a primitive root or not.
|
| 255 |
+
|
| 256 |
+
Parameters
|
| 257 |
+
==========
|
| 258 |
+
|
| 259 |
+
p : integer, p > 1
|
| 260 |
+
smallest : if True the smallest primitive root is returned or None
|
| 261 |
+
|
| 262 |
+
Returns
|
| 263 |
+
=======
|
| 264 |
+
|
| 265 |
+
int | None :
|
| 266 |
+
If the primitive root exists, return the primitive root of ``p``.
|
| 267 |
+
If not, return None.
|
| 268 |
+
|
| 269 |
+
Raises
|
| 270 |
+
======
|
| 271 |
+
|
| 272 |
+
ValueError
|
| 273 |
+
If `p \le 1` or ``p`` is not an integer.
|
| 274 |
+
|
| 275 |
+
Examples
|
| 276 |
+
========
|
| 277 |
+
|
| 278 |
+
>>> from sympy.ntheory.residue_ntheory import primitive_root
|
| 279 |
+
>>> primitive_root(19)
|
| 280 |
+
2
|
| 281 |
+
>>> primitive_root(21) is None
|
| 282 |
+
True
|
| 283 |
+
>>> primitive_root(50, smallest=False)
|
| 284 |
+
27
|
| 285 |
+
|
| 286 |
+
See Also
|
| 287 |
+
========
|
| 288 |
+
|
| 289 |
+
is_primitive_root
|
| 290 |
+
|
| 291 |
+
References
|
| 292 |
+
==========
|
| 293 |
+
|
| 294 |
+
.. [1] W. Stein "Elementary Number Theory" (2011), page 44
|
| 295 |
+
.. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
|
| 296 |
+
|
| 297 |
+
"""
|
| 298 |
+
p = as_int(p)
|
| 299 |
+
if p <= 1:
|
| 300 |
+
raise ValueError("p should be an integer greater than 1")
|
| 301 |
+
if p <= 4:
|
| 302 |
+
return p - 1
|
| 303 |
+
p_even = p % 2 == 0
|
| 304 |
+
if not p_even:
|
| 305 |
+
q = p # p is odd
|
| 306 |
+
elif p % 4:
|
| 307 |
+
q = p//2 # p had 1 factor of 2
|
| 308 |
+
else:
|
| 309 |
+
return None # p had more than one factor of 2
|
| 310 |
+
if isprime(q):
|
| 311 |
+
e = 1
|
| 312 |
+
else:
|
| 313 |
+
m = _perfect_power(q, 3)
|
| 314 |
+
if not m:
|
| 315 |
+
return None
|
| 316 |
+
q, e = m
|
| 317 |
+
if not isprime(q):
|
| 318 |
+
return None
|
| 319 |
+
if not smallest:
|
| 320 |
+
if p_even:
|
| 321 |
+
return next(_primitive_root_prime_power2_iter(q, e))
|
| 322 |
+
return next(_primitive_root_prime_power_iter(q, e))
|
| 323 |
+
if p_even:
|
| 324 |
+
for i in range(3, p, 2):
|
| 325 |
+
if i % q and is_primitive_root(i, p):
|
| 326 |
+
return i
|
| 327 |
+
g = next(_primitive_root_prime_iter(q))
|
| 328 |
+
if e == 1 or pow(g, q - 1, q**2) != 1:
|
| 329 |
+
return g
|
| 330 |
+
for i in range(g + 1, p):
|
| 331 |
+
if i % q and is_primitive_root(i, p):
|
| 332 |
+
return i
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def is_primitive_root(a, p):
|
| 336 |
+
r""" Returns True if ``a`` is a primitive root of ``p``.
|
| 337 |
+
|
| 338 |
+
Explanation
|
| 339 |
+
===========
|
| 340 |
+
|
| 341 |
+
``a`` is said to be the primitive root of ``p`` if `\gcd(a, p) = 1` and
|
| 342 |
+
`\phi(p)` is the smallest positive number s.t.
|
| 343 |
+
|
| 344 |
+
`a^{\phi(p)} \equiv 1 \pmod{p}`.
|
| 345 |
+
|
| 346 |
+
where `\phi(p)` is Euler's totient function.
|
| 347 |
+
|
| 348 |
+
The primitive root of ``p`` exist only for
|
| 349 |
+
`p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
|
| 350 |
+
Hence, if it is not such a ``p``, it returns False.
|
| 351 |
+
To determine the primitive root, we need to know
|
| 352 |
+
the prime factorization of ``q-1``.
|
| 353 |
+
The hardness of the determination depends on this complexity.
|
| 354 |
+
|
| 355 |
+
Parameters
|
| 356 |
+
==========
|
| 357 |
+
|
| 358 |
+
a : integer
|
| 359 |
+
p : integer, ``p`` > 1. ``a`` and ``p`` should be relatively prime
|
| 360 |
+
|
| 361 |
+
Returns
|
| 362 |
+
=======
|
| 363 |
+
|
| 364 |
+
bool : If True, ``a`` is the primitive root of ``p``.
|
| 365 |
+
|
| 366 |
+
Raises
|
| 367 |
+
======
|
| 368 |
+
|
| 369 |
+
ValueError
|
| 370 |
+
If `p \le 1` or `\gcd(a, p) \neq 1`.
|
| 371 |
+
If ``a`` or ``p`` is not an integer.
|
| 372 |
+
|
| 373 |
+
Examples
|
| 374 |
+
========
|
| 375 |
+
|
| 376 |
+
>>> from sympy.functions.combinatorial.numbers import totient
|
| 377 |
+
>>> from sympy.ntheory import is_primitive_root, n_order
|
| 378 |
+
>>> is_primitive_root(3, 10)
|
| 379 |
+
True
|
| 380 |
+
>>> is_primitive_root(9, 10)
|
| 381 |
+
False
|
| 382 |
+
>>> n_order(3, 10) == totient(10)
|
| 383 |
+
True
|
| 384 |
+
>>> n_order(9, 10) == totient(10)
|
| 385 |
+
False
|
| 386 |
+
|
| 387 |
+
See Also
|
| 388 |
+
========
|
| 389 |
+
|
| 390 |
+
primitive_root
|
| 391 |
+
|
| 392 |
+
"""
|
| 393 |
+
a, p = as_int(a), as_int(p)
|
| 394 |
+
if p <= 1:
|
| 395 |
+
raise ValueError("p should be an integer greater than 1")
|
| 396 |
+
a = a % p
|
| 397 |
+
if gcd(a, p) != 1:
|
| 398 |
+
raise ValueError("The two numbers should be relatively prime")
|
| 399 |
+
# Primitive root of p exist only for
|
| 400 |
+
# p = 2, 4, q**e, 2*q**e (q is odd prime)
|
| 401 |
+
if p <= 4:
|
| 402 |
+
# The primitive root is only p-1.
|
| 403 |
+
return a == p - 1
|
| 404 |
+
if p % 2:
|
| 405 |
+
q = p # p is odd
|
| 406 |
+
elif p % 4:
|
| 407 |
+
q = p//2 # p had 1 factor of 2
|
| 408 |
+
else:
|
| 409 |
+
return False # p had more than one factor of 2
|
| 410 |
+
if isprime(q):
|
| 411 |
+
group_order = q - 1
|
| 412 |
+
factors = factorint(q - 1).keys()
|
| 413 |
+
else:
|
| 414 |
+
m = _perfect_power(q, 3)
|
| 415 |
+
if not m:
|
| 416 |
+
return False
|
| 417 |
+
q, e = m
|
| 418 |
+
if not isprime(q):
|
| 419 |
+
return False
|
| 420 |
+
group_order = q**(e - 1)*(q - 1)
|
| 421 |
+
factors = set(factorint(q - 1).keys())
|
| 422 |
+
factors.add(q)
|
| 423 |
+
return all(pow(a, group_order // prime, p) != 1 for prime in factors)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _sqrt_mod_tonelli_shanks(a, p):
|
| 427 |
+
"""
|
| 428 |
+
Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
|
| 429 |
+
|
| 430 |
+
Assume that the root exists.
|
| 431 |
+
|
| 432 |
+
Parameters
|
| 433 |
+
==========
|
| 434 |
+
|
| 435 |
+
a : int
|
| 436 |
+
p : int
|
| 437 |
+
prime number. should be ``p % 8 == 1``
|
| 438 |
+
|
| 439 |
+
Returns
|
| 440 |
+
=======
|
| 441 |
+
|
| 442 |
+
int : Generally, there are two roots, but only one is returned.
|
| 443 |
+
Which one is returned is random.
|
| 444 |
+
|
| 445 |
+
Examples
|
| 446 |
+
========
|
| 447 |
+
|
| 448 |
+
>>> from sympy.ntheory.residue_ntheory import _sqrt_mod_tonelli_shanks
|
| 449 |
+
>>> _sqrt_mod_tonelli_shanks(2, 17) in [6, 11]
|
| 450 |
+
True
|
| 451 |
+
|
| 452 |
+
References
|
| 453 |
+
==========
|
| 454 |
+
|
| 455 |
+
.. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
|
| 456 |
+
2nd Edition (2005), page 101, ISBN:978-0387252827
|
| 457 |
+
|
| 458 |
+
"""
|
| 459 |
+
s = bit_scan1(p - 1)
|
| 460 |
+
t = p >> s
|
| 461 |
+
# find a non-quadratic residue
|
| 462 |
+
if p % 12 == 5:
|
| 463 |
+
# Legendre symbol (3/p) == -1 if p % 12 in [5, 7]
|
| 464 |
+
d = 3
|
| 465 |
+
elif p % 5 in [2, 3]:
|
| 466 |
+
# Legendre symbol (5/p) == -1 if p % 5 in [2, 3]
|
| 467 |
+
d = 5
|
| 468 |
+
else:
|
| 469 |
+
while 1:
|
| 470 |
+
d = randint(6, p - 1)
|
| 471 |
+
if jacobi(d, p) == -1:
|
| 472 |
+
break
|
| 473 |
+
#assert legendre_symbol(d, p) == -1
|
| 474 |
+
A = pow(a, t, p)
|
| 475 |
+
D = pow(d, t, p)
|
| 476 |
+
m = 0
|
| 477 |
+
for i in range(s):
|
| 478 |
+
adm = A*pow(D, m, p) % p
|
| 479 |
+
adm = pow(adm, 2**(s - 1 - i), p)
|
| 480 |
+
if adm % p == p - 1:
|
| 481 |
+
m += 2**i
|
| 482 |
+
#assert A*pow(D, m, p) % p == 1
|
| 483 |
+
x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
|
| 484 |
+
return x
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def sqrt_mod(a, p, all_roots=False):
|
| 488 |
+
"""
|
| 489 |
+
Find a root of ``x**2 = a mod p``.
|
| 490 |
+
|
| 491 |
+
Parameters
|
| 492 |
+
==========
|
| 493 |
+
|
| 494 |
+
a : integer
|
| 495 |
+
p : positive integer
|
| 496 |
+
all_roots : if True the list of roots is returned or None
|
| 497 |
+
|
| 498 |
+
Notes
|
| 499 |
+
=====
|
| 500 |
+
|
| 501 |
+
If there is no root it is returned None; else the returned root
|
| 502 |
+
is less or equal to ``p // 2``; in general is not the smallest one.
|
| 503 |
+
It is returned ``p // 2`` only if it is the only root.
|
| 504 |
+
|
| 505 |
+
Use ``all_roots`` only when it is expected that all the roots fit
|
| 506 |
+
in memory; otherwise use ``sqrt_mod_iter``.
|
| 507 |
+
|
| 508 |
+
Examples
|
| 509 |
+
========
|
| 510 |
+
|
| 511 |
+
>>> from sympy.ntheory import sqrt_mod
|
| 512 |
+
>>> sqrt_mod(11, 43)
|
| 513 |
+
21
|
| 514 |
+
>>> sqrt_mod(17, 32, True)
|
| 515 |
+
[7, 9, 23, 25]
|
| 516 |
+
"""
|
| 517 |
+
if all_roots:
|
| 518 |
+
return sorted(sqrt_mod_iter(a, p))
|
| 519 |
+
p = abs(as_int(p))
|
| 520 |
+
halfp = p // 2
|
| 521 |
+
x = None
|
| 522 |
+
for r in sqrt_mod_iter(a, p):
|
| 523 |
+
if r < halfp:
|
| 524 |
+
return r
|
| 525 |
+
elif r > halfp:
|
| 526 |
+
return p - r
|
| 527 |
+
else:
|
| 528 |
+
x = r
|
| 529 |
+
return x
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def sqrt_mod_iter(a, p, domain=int):
|
| 533 |
+
"""
|
| 534 |
+
Iterate over solutions to ``x**2 = a mod p``.
|
| 535 |
+
|
| 536 |
+
Parameters
|
| 537 |
+
==========
|
| 538 |
+
|
| 539 |
+
a : integer
|
| 540 |
+
p : positive integer
|
| 541 |
+
domain : integer domain, ``int``, ``ZZ`` or ``Integer``
|
| 542 |
+
|
| 543 |
+
Examples
|
| 544 |
+
========
|
| 545 |
+
|
| 546 |
+
>>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
|
| 547 |
+
>>> list(sqrt_mod_iter(11, 43))
|
| 548 |
+
[21, 22]
|
| 549 |
+
|
| 550 |
+
See Also
|
| 551 |
+
========
|
| 552 |
+
|
| 553 |
+
sqrt_mod : Same functionality, but you want a sorted list or only one solution.
|
| 554 |
+
|
| 555 |
+
"""
|
| 556 |
+
a, p = as_int(a), abs(as_int(p))
|
| 557 |
+
v = []
|
| 558 |
+
pv = []
|
| 559 |
+
_product = product
|
| 560 |
+
for px, ex in factorint(p).items():
|
| 561 |
+
if a % px:
|
| 562 |
+
# `len(rx)` is at most 4
|
| 563 |
+
rx = _sqrt_mod_prime_power(a, px, ex)
|
| 564 |
+
else:
|
| 565 |
+
# `len(list(rx))` can be assumed to be large.
|
| 566 |
+
# The `itertools.product` is disadvantageous in terms of memory usage.
|
| 567 |
+
# It is also inferior to iproduct in speed if not all Cartesian products are needed.
|
| 568 |
+
rx = _sqrt_mod1(a, px, ex)
|
| 569 |
+
_product = iproduct
|
| 570 |
+
if not rx:
|
| 571 |
+
return
|
| 572 |
+
v.append(rx)
|
| 573 |
+
pv.append(px**ex)
|
| 574 |
+
if len(v) == 1:
|
| 575 |
+
yield from map(domain, v[0])
|
| 576 |
+
else:
|
| 577 |
+
mm, e, s = gf_crt1(pv, ZZ)
|
| 578 |
+
for vx in _product(*v):
|
| 579 |
+
yield domain(gf_crt2(vx, pv, mm, e, s, ZZ))
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _sqrt_mod_prime_power(a, p, k):
|
| 583 |
+
"""
|
| 584 |
+
Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``.
|
| 585 |
+
If no solution exists, return ``None``.
|
| 586 |
+
Solutions are returned in an ascending list.
|
| 587 |
+
|
| 588 |
+
Parameters
|
| 589 |
+
==========
|
| 590 |
+
|
| 591 |
+
a : integer
|
| 592 |
+
p : prime number
|
| 593 |
+
k : positive integer
|
| 594 |
+
|
| 595 |
+
Examples
|
| 596 |
+
========
|
| 597 |
+
|
| 598 |
+
>>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
|
| 599 |
+
>>> _sqrt_mod_prime_power(11, 43, 1)
|
| 600 |
+
[21, 22]
|
| 601 |
+
|
| 602 |
+
References
|
| 603 |
+
==========
|
| 604 |
+
|
| 605 |
+
.. [1] P. Hackman "Elementary Number Theory" (2009), page 160
|
| 606 |
+
.. [2] http://www.numbertheory.org/php/squareroot.html
|
| 607 |
+
.. [3] [Gathen99]_
|
| 608 |
+
"""
|
| 609 |
+
pk = p**k
|
| 610 |
+
a = a % pk
|
| 611 |
+
|
| 612 |
+
if p == 2:
|
| 613 |
+
# see Ref.[2]
|
| 614 |
+
if a % 8 != 1:
|
| 615 |
+
return None
|
| 616 |
+
# Trivial
|
| 617 |
+
if k <= 3:
|
| 618 |
+
return list(range(1, pk, 2))
|
| 619 |
+
r = 1
|
| 620 |
+
# r is one of the solutions to x**2 - a = 0 (mod 2**3).
|
| 621 |
+
# Hensel lift them to solutions of x**2 - a = 0 (mod 2**k)
|
| 622 |
+
# if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
|
| 623 |
+
# then r + 2**(nx - 1) is a root mod 2**(nx+1)
|
| 624 |
+
for nx in range(3, k):
|
| 625 |
+
if ((r**2 - a) >> nx) % 2:
|
| 626 |
+
r += 1 << (nx - 1)
|
| 627 |
+
# r is a solution of x**2 - a = 0 (mod 2**k), and
|
| 628 |
+
# there exist other solutions -r, r+h, -(r+h), and these are all solutions.
|
| 629 |
+
h = 1 << (k - 1)
|
| 630 |
+
return sorted([r, pk - r, (r + h) % pk, -(r + h) % pk])
|
| 631 |
+
|
| 632 |
+
# If the Legendre symbol (a/p) is not 1, no solution exists.
|
| 633 |
+
if jacobi(a, p) != 1:
|
| 634 |
+
return None
|
| 635 |
+
if p % 4 == 3:
|
| 636 |
+
res = pow(a, (p + 1) // 4, p)
|
| 637 |
+
elif p % 8 == 5:
|
| 638 |
+
res = pow(a, (p + 3) // 8, p)
|
| 639 |
+
if pow(res, 2, p) != a % p:
|
| 640 |
+
res = res * pow(2, (p - 1) // 4, p) % p
|
| 641 |
+
else:
|
| 642 |
+
res = _sqrt_mod_tonelli_shanks(a, p)
|
| 643 |
+
if k > 1:
|
| 644 |
+
# Hensel lifting with Newton iteration, see Ref.[3] chapter 9
|
| 645 |
+
# with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
|
| 646 |
+
px = p
|
| 647 |
+
for _ in range(k.bit_length() - 1):
|
| 648 |
+
px = px**2
|
| 649 |
+
frinv = invert(2*res, px)
|
| 650 |
+
res = (res - (res**2 - a)*frinv) % px
|
| 651 |
+
if k & (k - 1): # If k is not a power of 2
|
| 652 |
+
frinv = invert(2*res, pk)
|
| 653 |
+
res = (res - (res**2 - a)*frinv) % pk
|
| 654 |
+
return sorted([res, pk - res])
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _sqrt_mod1(a, p, n):
|
| 658 |
+
"""
|
| 659 |
+
Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``.
|
| 660 |
+
If no solution exists, return ``None``.
|
| 661 |
+
|
| 662 |
+
Parameters
|
| 663 |
+
==========
|
| 664 |
+
|
| 665 |
+
a : integer
|
| 666 |
+
p : prime number, p must divide a
|
| 667 |
+
n : positive integer
|
| 668 |
+
|
| 669 |
+
References
|
| 670 |
+
==========
|
| 671 |
+
|
| 672 |
+
.. [1] http://www.numbertheory.org/php/squareroot.html
|
| 673 |
+
"""
|
| 674 |
+
pn = p**n
|
| 675 |
+
a = a % pn
|
| 676 |
+
if a == 0:
|
| 677 |
+
# case gcd(a, p**k) = p**n
|
| 678 |
+
return range(0, pn, p**((n + 1) // 2))
|
| 679 |
+
# case gcd(a, p**k) = p**r, r < n
|
| 680 |
+
a, r = remove(a, p)
|
| 681 |
+
if r % 2 == 1:
|
| 682 |
+
return None
|
| 683 |
+
res = _sqrt_mod_prime_power(a, p, n - r)
|
| 684 |
+
if res is None:
|
| 685 |
+
return None
|
| 686 |
+
m = r // 2
|
| 687 |
+
return (x for rx in res for x in range(rx*p**m, pn, p**(n - m)))
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def is_quad_residue(a, p):
|
| 691 |
+
"""
|
| 692 |
+
Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
|
| 693 |
+
i.e a % p in set([i**2 % p for i in range(p)]).
|
| 694 |
+
|
| 695 |
+
Parameters
|
| 696 |
+
==========
|
| 697 |
+
|
| 698 |
+
a : integer
|
| 699 |
+
p : positive integer
|
| 700 |
+
|
| 701 |
+
Returns
|
| 702 |
+
=======
|
| 703 |
+
|
| 704 |
+
bool : If True, ``x**2 == a (mod p)`` has solution.
|
| 705 |
+
|
| 706 |
+
Raises
|
| 707 |
+
======
|
| 708 |
+
|
| 709 |
+
ValueError
|
| 710 |
+
If ``a``, ``p`` is not integer.
|
| 711 |
+
If ``p`` is not positive.
|
| 712 |
+
|
| 713 |
+
Examples
|
| 714 |
+
========
|
| 715 |
+
|
| 716 |
+
>>> from sympy.ntheory import is_quad_residue
|
| 717 |
+
>>> is_quad_residue(21, 100)
|
| 718 |
+
True
|
| 719 |
+
|
| 720 |
+
Indeed, ``pow(39, 2, 100)`` would be 21.
|
| 721 |
+
|
| 722 |
+
>>> is_quad_residue(21, 120)
|
| 723 |
+
False
|
| 724 |
+
|
| 725 |
+
That is, for any integer ``x``, ``pow(x, 2, 120)`` is not 21.
|
| 726 |
+
|
| 727 |
+
If ``p`` is an odd
|
| 728 |
+
prime, an iterative method is used to make the determination:
|
| 729 |
+
|
| 730 |
+
>>> from sympy.ntheory import is_quad_residue
|
| 731 |
+
>>> sorted(set([i**2 % 7 for i in range(7)]))
|
| 732 |
+
[0, 1, 2, 4]
|
| 733 |
+
>>> [j for j in range(7) if is_quad_residue(j, 7)]
|
| 734 |
+
[0, 1, 2, 4]
|
| 735 |
+
|
| 736 |
+
See Also
|
| 737 |
+
========
|
| 738 |
+
|
| 739 |
+
legendre_symbol, jacobi_symbol, sqrt_mod
|
| 740 |
+
"""
|
| 741 |
+
a, p = as_int(a), as_int(p)
|
| 742 |
+
if p < 1:
|
| 743 |
+
raise ValueError('p must be > 0')
|
| 744 |
+
a %= p
|
| 745 |
+
if a < 2 or p < 3:
|
| 746 |
+
return True
|
| 747 |
+
# Since we want to compute the Jacobi symbol,
|
| 748 |
+
# we separate p into the odd part and the rest.
|
| 749 |
+
t = bit_scan1(p)
|
| 750 |
+
if t:
|
| 751 |
+
# The existence of a solution to a power of 2 is determined
|
| 752 |
+
# using the logic of `p==2` in `_sqrt_mod_prime_power` and `_sqrt_mod1`.
|
| 753 |
+
a_ = a % (1 << t)
|
| 754 |
+
if a_:
|
| 755 |
+
r = bit_scan1(a_)
|
| 756 |
+
if r % 2 or (a_ >> r) & 6:
|
| 757 |
+
return False
|
| 758 |
+
p >>= t
|
| 759 |
+
a %= p
|
| 760 |
+
if a < 2 or p < 3:
|
| 761 |
+
return True
|
| 762 |
+
# If Jacobi symbol is -1 or p is prime, can be determined by Jacobi symbol only
|
| 763 |
+
j = jacobi(a, p)
|
| 764 |
+
if j == -1 or isprime(p):
|
| 765 |
+
return j == 1
|
| 766 |
+
# Checks if `x**2 = a (mod p)` has a solution
|
| 767 |
+
for px, ex in factorint(p).items():
|
| 768 |
+
if a % px:
|
| 769 |
+
if jacobi(a, px) != 1:
|
| 770 |
+
return False
|
| 771 |
+
else:
|
| 772 |
+
a_ = a % px**ex
|
| 773 |
+
if a_ == 0:
|
| 774 |
+
continue
|
| 775 |
+
a_, r = remove(a_, px)
|
| 776 |
+
if r % 2 or jacobi(a_, px) != 1:
|
| 777 |
+
return False
|
| 778 |
+
return True
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def is_nthpow_residue(a, n, m):
|
| 782 |
+
"""
|
| 783 |
+
Returns True if ``x**n == a (mod m)`` has solutions.
|
| 784 |
+
|
| 785 |
+
References
|
| 786 |
+
==========
|
| 787 |
+
|
| 788 |
+
.. [1] P. Hackman "Elementary Number Theory" (2009), page 76
|
| 789 |
+
|
| 790 |
+
"""
|
| 791 |
+
a = a % m
|
| 792 |
+
a, n, m = as_int(a), as_int(n), as_int(m)
|
| 793 |
+
if m <= 0:
|
| 794 |
+
raise ValueError('m must be > 0')
|
| 795 |
+
if n < 0:
|
| 796 |
+
raise ValueError('n must be >= 0')
|
| 797 |
+
if n == 0:
|
| 798 |
+
if m == 1:
|
| 799 |
+
return False
|
| 800 |
+
return a == 1
|
| 801 |
+
if a == 0:
|
| 802 |
+
return True
|
| 803 |
+
if n == 1:
|
| 804 |
+
return True
|
| 805 |
+
if n == 2:
|
| 806 |
+
return is_quad_residue(a, m)
|
| 807 |
+
return all(_is_nthpow_residue_bign_prime_power(a, n, p, e)
|
| 808 |
+
for p, e in factorint(m).items())
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def _is_nthpow_residue_bign_prime_power(a, n, p, k):
|
| 812 |
+
r"""
|
| 813 |
+
Returns True if `x^n = a \pmod{p^k}` has solutions for `n > 2`.
|
| 814 |
+
|
| 815 |
+
Parameters
|
| 816 |
+
==========
|
| 817 |
+
|
| 818 |
+
a : positive integer
|
| 819 |
+
n : integer, n > 2
|
| 820 |
+
p : prime number
|
| 821 |
+
k : positive integer
|
| 822 |
+
|
| 823 |
+
"""
|
| 824 |
+
while a % p == 0:
|
| 825 |
+
a %= pow(p, k)
|
| 826 |
+
if not a:
|
| 827 |
+
return True
|
| 828 |
+
a, mu = remove(a, p)
|
| 829 |
+
if mu % n:
|
| 830 |
+
return False
|
| 831 |
+
k -= mu
|
| 832 |
+
if p != 2:
|
| 833 |
+
f = p**(k - 1)*(p - 1) # f = totient(p**k)
|
| 834 |
+
return pow(a, f // gcd(f, n), pow(p, k)) == 1
|
| 835 |
+
if n & 1:
|
| 836 |
+
return True
|
| 837 |
+
c = min(bit_scan1(n) + 2, k)
|
| 838 |
+
return a % pow(2, c) == 1
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
def _nthroot_mod1(s, q, p, all_roots):
|
| 842 |
+
"""
|
| 843 |
+
Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``.
|
| 844 |
+
Assume that the root exists.
|
| 845 |
+
|
| 846 |
+
Parameters
|
| 847 |
+
==========
|
| 848 |
+
|
| 849 |
+
s : integer
|
| 850 |
+
q : integer, n > 2. ``q`` divides ``p - 1``.
|
| 851 |
+
p : prime number
|
| 852 |
+
all_roots : if False returns the smallest root, else the list of roots
|
| 853 |
+
|
| 854 |
+
Returns
|
| 855 |
+
=======
|
| 856 |
+
|
| 857 |
+
list[int] | int :
|
| 858 |
+
Root of ``x**q = s mod p``. If ``all_roots == True``,
|
| 859 |
+
returned ascending list. otherwise, returned an int.
|
| 860 |
+
|
| 861 |
+
Examples
|
| 862 |
+
========
|
| 863 |
+
|
| 864 |
+
>>> from sympy.ntheory.residue_ntheory import _nthroot_mod1
|
| 865 |
+
>>> _nthroot_mod1(5, 3, 13, False)
|
| 866 |
+
7
|
| 867 |
+
>>> _nthroot_mod1(13, 4, 17, True)
|
| 868 |
+
[3, 5, 12, 14]
|
| 869 |
+
|
| 870 |
+
References
|
| 871 |
+
==========
|
| 872 |
+
|
| 873 |
+
.. [1] A. M. Johnston, A Generalized qth Root Algorithm,
|
| 874 |
+
ACM-SIAM Symposium on Discrete Algorithms (1999), pp. 929-930
|
| 875 |
+
|
| 876 |
+
"""
|
| 877 |
+
g = next(_primitive_root_prime_iter(p))
|
| 878 |
+
r = s
|
| 879 |
+
for qx, ex in factorint(q).items():
|
| 880 |
+
f = (p - 1) // qx**ex
|
| 881 |
+
while f % qx == 0:
|
| 882 |
+
f //= qx
|
| 883 |
+
z = f*invert(-f, qx)
|
| 884 |
+
x = (1 + z) // qx
|
| 885 |
+
t = discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
|
| 886 |
+
for _ in range(ex):
|
| 887 |
+
# assert t == discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
|
| 888 |
+
r = pow(r, x, p)*pow(g, -z*t % (p - 1), p) % p
|
| 889 |
+
t //= qx
|
| 890 |
+
res = [r]
|
| 891 |
+
h = pow(g, (p - 1) // q, p)
|
| 892 |
+
#assert pow(h, q, p) == 1
|
| 893 |
+
hx = r
|
| 894 |
+
for _ in range(q - 1):
|
| 895 |
+
hx = (hx*h) % p
|
| 896 |
+
res.append(hx)
|
| 897 |
+
if all_roots:
|
| 898 |
+
res.sort()
|
| 899 |
+
return res
|
| 900 |
+
return min(res)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def _nthroot_mod_prime_power(a, n, p, k):
|
| 904 |
+
""" Root of ``x**n = a mod p**k``.
|
| 905 |
+
|
| 906 |
+
Parameters
|
| 907 |
+
==========
|
| 908 |
+
|
| 909 |
+
a : integer
|
| 910 |
+
n : integer, n > 2
|
| 911 |
+
p : prime number
|
| 912 |
+
k : positive integer
|
| 913 |
+
|
| 914 |
+
Returns
|
| 915 |
+
=======
|
| 916 |
+
|
| 917 |
+
list[int] :
|
| 918 |
+
Ascending list of roots of ``x**n = a mod p**k``.
|
| 919 |
+
If no solution exists, return ``[]``.
|
| 920 |
+
|
| 921 |
+
"""
|
| 922 |
+
if not _is_nthpow_residue_bign_prime_power(a, n, p, k):
|
| 923 |
+
return []
|
| 924 |
+
a_mod_p = a % p
|
| 925 |
+
if a_mod_p == 0:
|
| 926 |
+
base_roots = [0]
|
| 927 |
+
elif (p - 1) % n == 0:
|
| 928 |
+
base_roots = _nthroot_mod1(a_mod_p, n, p, all_roots=True)
|
| 929 |
+
else:
|
| 930 |
+
# The roots of ``x**n - a = 0 (mod p)`` are roots of
|
| 931 |
+
# ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
|
| 932 |
+
pa = n
|
| 933 |
+
pb = p - 1
|
| 934 |
+
b = 1
|
| 935 |
+
if pa < pb:
|
| 936 |
+
a_mod_p, pa, b, pb = b, pb, a_mod_p, pa
|
| 937 |
+
# gcd(x**pa - a, x**pb - b) = gcd(x**pb - b, x**pc - c)
|
| 938 |
+
# where pc = pa % pb; c = b**-q * a mod p
|
| 939 |
+
while pb:
|
| 940 |
+
q, pc = divmod(pa, pb)
|
| 941 |
+
c = pow(b, -q, p) * a_mod_p % p
|
| 942 |
+
pa, pb = pb, pc
|
| 943 |
+
a_mod_p, b = b, c
|
| 944 |
+
if pa == 1:
|
| 945 |
+
base_roots = [a_mod_p]
|
| 946 |
+
elif pa == 2:
|
| 947 |
+
base_roots = sqrt_mod(a_mod_p, p, all_roots=True)
|
| 948 |
+
else:
|
| 949 |
+
base_roots = _nthroot_mod1(a_mod_p, pa, p, all_roots=True)
|
| 950 |
+
if k == 1:
|
| 951 |
+
return base_roots
|
| 952 |
+
a %= p**k
|
| 953 |
+
tot_roots = set()
|
| 954 |
+
for root in base_roots:
|
| 955 |
+
diff = pow(root, n - 1, p)*n % p
|
| 956 |
+
new_base = p
|
| 957 |
+
if diff != 0:
|
| 958 |
+
m_inv = invert(diff, p)
|
| 959 |
+
for _ in range(k - 1):
|
| 960 |
+
new_base *= p
|
| 961 |
+
tmp = pow(root, n, new_base) - a
|
| 962 |
+
tmp *= m_inv
|
| 963 |
+
root = (root - tmp) % new_base
|
| 964 |
+
tot_roots.add(root)
|
| 965 |
+
else:
|
| 966 |
+
roots_in_base = {root}
|
| 967 |
+
for _ in range(k - 1):
|
| 968 |
+
new_base *= p
|
| 969 |
+
new_roots = set()
|
| 970 |
+
for k_ in roots_in_base:
|
| 971 |
+
if pow(k_, n, new_base) != a % new_base:
|
| 972 |
+
continue
|
| 973 |
+
while k_ not in new_roots:
|
| 974 |
+
new_roots.add(k_)
|
| 975 |
+
k_ = (k_ + (new_base // p)) % new_base
|
| 976 |
+
roots_in_base = new_roots
|
| 977 |
+
tot_roots = tot_roots | roots_in_base
|
| 978 |
+
return sorted(tot_roots)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def nthroot_mod(a, n, p, all_roots=False):
|
| 982 |
+
"""
|
| 983 |
+
Find the solutions to ``x**n = a mod p``.
|
| 984 |
+
|
| 985 |
+
Parameters
|
| 986 |
+
==========
|
| 987 |
+
|
| 988 |
+
a : integer
|
| 989 |
+
n : positive integer
|
| 990 |
+
p : positive integer
|
| 991 |
+
all_roots : if False returns the smallest root, else the list of roots
|
| 992 |
+
|
| 993 |
+
Returns
|
| 994 |
+
=======
|
| 995 |
+
|
| 996 |
+
list[int] | int | None :
|
| 997 |
+
solutions to ``x**n = a mod p``.
|
| 998 |
+
The table of the output type is:
|
| 999 |
+
|
| 1000 |
+
========== ========== ==========
|
| 1001 |
+
all_roots has roots Returns
|
| 1002 |
+
========== ========== ==========
|
| 1003 |
+
True Yes list[int]
|
| 1004 |
+
True No []
|
| 1005 |
+
False Yes int
|
| 1006 |
+
False No None
|
| 1007 |
+
========== ========== ==========
|
| 1008 |
+
|
| 1009 |
+
Raises
|
| 1010 |
+
======
|
| 1011 |
+
|
| 1012 |
+
ValueError
|
| 1013 |
+
If ``a``, ``n`` or ``p`` is not integer.
|
| 1014 |
+
If ``n`` or ``p`` is not positive.
|
| 1015 |
+
|
| 1016 |
+
Examples
|
| 1017 |
+
========
|
| 1018 |
+
|
| 1019 |
+
>>> from sympy.ntheory.residue_ntheory import nthroot_mod
|
| 1020 |
+
>>> nthroot_mod(11, 4, 19)
|
| 1021 |
+
8
|
| 1022 |
+
>>> nthroot_mod(11, 4, 19, True)
|
| 1023 |
+
[8, 11]
|
| 1024 |
+
>>> nthroot_mod(68, 3, 109)
|
| 1025 |
+
23
|
| 1026 |
+
|
| 1027 |
+
References
|
| 1028 |
+
==========
|
| 1029 |
+
|
| 1030 |
+
.. [1] P. Hackman "Elementary Number Theory" (2009), page 76
|
| 1031 |
+
|
| 1032 |
+
"""
|
| 1033 |
+
a = a % p
|
| 1034 |
+
a, n, p = as_int(a), as_int(n), as_int(p)
|
| 1035 |
+
|
| 1036 |
+
if n < 1:
|
| 1037 |
+
raise ValueError("n should be positive")
|
| 1038 |
+
if p < 1:
|
| 1039 |
+
raise ValueError("p should be positive")
|
| 1040 |
+
if n == 1:
|
| 1041 |
+
return [a] if all_roots else a
|
| 1042 |
+
if n == 2:
|
| 1043 |
+
return sqrt_mod(a, p, all_roots)
|
| 1044 |
+
base = []
|
| 1045 |
+
prime_power = []
|
| 1046 |
+
for q, e in factorint(p).items():
|
| 1047 |
+
tot_roots = _nthroot_mod_prime_power(a, n, q, e)
|
| 1048 |
+
if not tot_roots:
|
| 1049 |
+
return [] if all_roots else None
|
| 1050 |
+
prime_power.append(q**e)
|
| 1051 |
+
base.append(sorted(tot_roots))
|
| 1052 |
+
P, E, S = gf_crt1(prime_power, ZZ)
|
| 1053 |
+
ret = sorted(map(int, {gf_crt2(c, prime_power, P, E, S, ZZ)
|
| 1054 |
+
for c in product(*base)}))
|
| 1055 |
+
if all_roots:
|
| 1056 |
+
return ret
|
| 1057 |
+
if ret:
|
| 1058 |
+
return ret[0]
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def quadratic_residues(p) -> list[int]:
|
| 1062 |
+
"""
|
| 1063 |
+
Returns the list of quadratic residues.
|
| 1064 |
+
|
| 1065 |
+
Examples
|
| 1066 |
+
========
|
| 1067 |
+
|
| 1068 |
+
>>> from sympy.ntheory.residue_ntheory import quadratic_residues
|
| 1069 |
+
>>> quadratic_residues(7)
|
| 1070 |
+
[0, 1, 2, 4]
|
| 1071 |
+
"""
|
| 1072 |
+
p = as_int(p)
|
| 1073 |
+
r = {pow(i, 2, p) for i in range(p // 2 + 1)}
|
| 1074 |
+
return sorted(r)
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
@deprecated("""\
|
| 1078 |
+
The `sympy.ntheory.residue_ntheory.legendre_symbol` has been moved to `sympy.functions.combinatorial.numbers.legendre_symbol`.""",
|
| 1079 |
+
deprecated_since_version="1.13",
|
| 1080 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 1081 |
+
def legendre_symbol(a, p):
|
| 1082 |
+
r"""
|
| 1083 |
+
Returns the Legendre symbol `(a / p)`.
|
| 1084 |
+
|
| 1085 |
+
.. deprecated:: 1.13
|
| 1086 |
+
|
| 1087 |
+
The ``legendre_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.legendre_symbol`
|
| 1088 |
+
instead. See its documentation for more information. See
|
| 1089 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 1090 |
+
|
| 1091 |
+
For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
|
| 1092 |
+
defined as
|
| 1093 |
+
|
| 1094 |
+
.. math ::
|
| 1095 |
+
\genfrac(){}{}{a}{p} = \begin{cases}
|
| 1096 |
+
0 & \text{if } p \text{ divides } a\\
|
| 1097 |
+
1 & \text{if } a \text{ is a quadratic residue modulo } p\\
|
| 1098 |
+
-1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
|
| 1099 |
+
\end{cases}
|
| 1100 |
+
|
| 1101 |
+
Parameters
|
| 1102 |
+
==========
|
| 1103 |
+
|
| 1104 |
+
a : integer
|
| 1105 |
+
p : odd prime
|
| 1106 |
+
|
| 1107 |
+
Examples
|
| 1108 |
+
========
|
| 1109 |
+
|
| 1110 |
+
>>> from sympy.functions.combinatorial.numbers import legendre_symbol
|
| 1111 |
+
>>> [legendre_symbol(i, 7) for i in range(7)]
|
| 1112 |
+
[0, 1, 1, -1, 1, -1, -1]
|
| 1113 |
+
>>> sorted(set([i**2 % 7 for i in range(7)]))
|
| 1114 |
+
[0, 1, 2, 4]
|
| 1115 |
+
|
| 1116 |
+
See Also
|
| 1117 |
+
========
|
| 1118 |
+
|
| 1119 |
+
is_quad_residue, jacobi_symbol
|
| 1120 |
+
|
| 1121 |
+
"""
|
| 1122 |
+
from sympy.functions.combinatorial.numbers import legendre_symbol as _legendre_symbol
|
| 1123 |
+
return _legendre_symbol(a, p)
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
@deprecated("""\
|
| 1127 |
+
The `sympy.ntheory.residue_ntheory.jacobi_symbol` has been moved to `sympy.functions.combinatorial.numbers.jacobi_symbol`.""",
|
| 1128 |
+
deprecated_since_version="1.13",
|
| 1129 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 1130 |
+
def jacobi_symbol(m, n):
|
| 1131 |
+
r"""
|
| 1132 |
+
Returns the Jacobi symbol `(m / n)`.
|
| 1133 |
+
|
| 1134 |
+
.. deprecated:: 1.13
|
| 1135 |
+
|
| 1136 |
+
The ``jacobi_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.jacobi_symbol`
|
| 1137 |
+
instead. See its documentation for more information. See
|
| 1138 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 1139 |
+
|
| 1140 |
+
For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
|
| 1141 |
+
is defined as the product of the Legendre symbols corresponding to the
|
| 1142 |
+
prime factors of ``n``:
|
| 1143 |
+
|
| 1144 |
+
.. math ::
|
| 1145 |
+
\genfrac(){}{}{m}{n} =
|
| 1146 |
+
\genfrac(){}{}{m}{p^{1}}^{\alpha_1}
|
| 1147 |
+
\genfrac(){}{}{m}{p^{2}}^{\alpha_2}
|
| 1148 |
+
...
|
| 1149 |
+
\genfrac(){}{}{m}{p^{k}}^{\alpha_k}
|
| 1150 |
+
\text{ where } n =
|
| 1151 |
+
p_1^{\alpha_1}
|
| 1152 |
+
p_2^{\alpha_2}
|
| 1153 |
+
...
|
| 1154 |
+
p_k^{\alpha_k}
|
| 1155 |
+
|
| 1156 |
+
Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
|
| 1157 |
+
then ``m`` is a quadratic nonresidue modulo ``n``.
|
| 1158 |
+
|
| 1159 |
+
But, unlike the Legendre symbol, if the Jacobi symbol
|
| 1160 |
+
`\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
|
| 1161 |
+
modulo ``n``.
|
| 1162 |
+
|
| 1163 |
+
Parameters
|
| 1164 |
+
==========
|
| 1165 |
+
|
| 1166 |
+
m : integer
|
| 1167 |
+
n : odd positive integer
|
| 1168 |
+
|
| 1169 |
+
Examples
|
| 1170 |
+
========
|
| 1171 |
+
|
| 1172 |
+
>>> from sympy.functions.combinatorial.numbers import jacobi_symbol, legendre_symbol
|
| 1173 |
+
>>> from sympy import S
|
| 1174 |
+
>>> jacobi_symbol(45, 77)
|
| 1175 |
+
-1
|
| 1176 |
+
>>> jacobi_symbol(60, 121)
|
| 1177 |
+
1
|
| 1178 |
+
|
| 1179 |
+
The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
|
| 1180 |
+
be demonstrated as follows:
|
| 1181 |
+
|
| 1182 |
+
>>> L = legendre_symbol
|
| 1183 |
+
>>> S(45).factors()
|
| 1184 |
+
{3: 2, 5: 1}
|
| 1185 |
+
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
|
| 1186 |
+
True
|
| 1187 |
+
|
| 1188 |
+
See Also
|
| 1189 |
+
========
|
| 1190 |
+
|
| 1191 |
+
is_quad_residue, legendre_symbol
|
| 1192 |
+
"""
|
| 1193 |
+
from sympy.functions.combinatorial.numbers import jacobi_symbol as _jacobi_symbol
|
| 1194 |
+
return _jacobi_symbol(m, n)
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
@deprecated("""\
|
| 1198 |
+
The `sympy.ntheory.residue_ntheory.mobius` has been moved to `sympy.functions.combinatorial.numbers.mobius`.""",
|
| 1199 |
+
deprecated_since_version="1.13",
|
| 1200 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 1201 |
+
def mobius(n):
|
| 1202 |
+
"""
|
| 1203 |
+
Mobius function maps natural number to {-1, 0, 1}
|
| 1204 |
+
|
| 1205 |
+
.. deprecated:: 1.13
|
| 1206 |
+
|
| 1207 |
+
The ``mobius`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.mobius`
|
| 1208 |
+
instead. See its documentation for more information. See
|
| 1209 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 1210 |
+
|
| 1211 |
+
It is defined as follows:
|
| 1212 |
+
1) `1` if `n = 1`.
|
| 1213 |
+
2) `0` if `n` has a squared prime factor.
|
| 1214 |
+
3) `(-1)^k` if `n` is a square-free positive integer with `k`
|
| 1215 |
+
number of prime factors.
|
| 1216 |
+
|
| 1217 |
+
It is an important multiplicative function in number theory
|
| 1218 |
+
and combinatorics. It has applications in mathematical series,
|
| 1219 |
+
algebraic number theory and also physics (Fermion operator has very
|
| 1220 |
+
concrete realization with Mobius Function model).
|
| 1221 |
+
|
| 1222 |
+
Parameters
|
| 1223 |
+
==========
|
| 1224 |
+
|
| 1225 |
+
n : positive integer
|
| 1226 |
+
|
| 1227 |
+
Examples
|
| 1228 |
+
========
|
| 1229 |
+
|
| 1230 |
+
>>> from sympy.functions.combinatorial.numbers import mobius
|
| 1231 |
+
>>> mobius(13*7)
|
| 1232 |
+
1
|
| 1233 |
+
>>> mobius(1)
|
| 1234 |
+
1
|
| 1235 |
+
>>> mobius(13*7*5)
|
| 1236 |
+
-1
|
| 1237 |
+
>>> mobius(13**2)
|
| 1238 |
+
0
|
| 1239 |
+
|
| 1240 |
+
References
|
| 1241 |
+
==========
|
| 1242 |
+
|
| 1243 |
+
.. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
|
| 1244 |
+
.. [2] Thomas Koshy "Elementary Number Theory with Applications"
|
| 1245 |
+
|
| 1246 |
+
"""
|
| 1247 |
+
from sympy.functions.combinatorial.numbers import mobius as _mobius
|
| 1248 |
+
return _mobius(n)
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
def _discrete_log_trial_mul(n, a, b, order=None):
|
| 1252 |
+
"""
|
| 1253 |
+
Trial multiplication algorithm for computing the discrete logarithm of
|
| 1254 |
+
``a`` to the base ``b`` modulo ``n``.
|
| 1255 |
+
|
| 1256 |
+
The algorithm finds the discrete logarithm using exhaustive search. This
|
| 1257 |
+
naive method is used as fallback algorithm of ``discrete_log`` when the
|
| 1258 |
+
group order is very small.
|
| 1259 |
+
|
| 1260 |
+
Examples
|
| 1261 |
+
========
|
| 1262 |
+
|
| 1263 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
|
| 1264 |
+
>>> _discrete_log_trial_mul(41, 15, 7)
|
| 1265 |
+
3
|
| 1266 |
+
|
| 1267 |
+
See Also
|
| 1268 |
+
========
|
| 1269 |
+
|
| 1270 |
+
discrete_log
|
| 1271 |
+
|
| 1272 |
+
References
|
| 1273 |
+
==========
|
| 1274 |
+
|
| 1275 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1276 |
+
Vanstone, S. A. (1997).
|
| 1277 |
+
"""
|
| 1278 |
+
a %= n
|
| 1279 |
+
b %= n
|
| 1280 |
+
if order is None:
|
| 1281 |
+
order = n
|
| 1282 |
+
x = 1
|
| 1283 |
+
for i in range(order):
|
| 1284 |
+
if x == a:
|
| 1285 |
+
return i
|
| 1286 |
+
x = x * b % n
|
| 1287 |
+
raise ValueError("Log does not exist")
|
| 1288 |
+
|
| 1289 |
+
|
| 1290 |
+
def _discrete_log_shanks_steps(n, a, b, order=None):
|
| 1291 |
+
"""
|
| 1292 |
+
Baby-step giant-step algorithm for computing the discrete logarithm of
|
| 1293 |
+
``a`` to the base ``b`` modulo ``n``.
|
| 1294 |
+
|
| 1295 |
+
The algorithm is a time-memory trade-off of the method of exhaustive
|
| 1296 |
+
search. It uses `O(sqrt(m))` memory, where `m` is the group order.
|
| 1297 |
+
|
| 1298 |
+
Examples
|
| 1299 |
+
========
|
| 1300 |
+
|
| 1301 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
|
| 1302 |
+
>>> _discrete_log_shanks_steps(41, 15, 7)
|
| 1303 |
+
3
|
| 1304 |
+
|
| 1305 |
+
See Also
|
| 1306 |
+
========
|
| 1307 |
+
|
| 1308 |
+
discrete_log
|
| 1309 |
+
|
| 1310 |
+
References
|
| 1311 |
+
==========
|
| 1312 |
+
|
| 1313 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1314 |
+
Vanstone, S. A. (1997).
|
| 1315 |
+
"""
|
| 1316 |
+
a %= n
|
| 1317 |
+
b %= n
|
| 1318 |
+
if order is None:
|
| 1319 |
+
order = n_order(b, n)
|
| 1320 |
+
m = sqrt(order) + 1
|
| 1321 |
+
T = {}
|
| 1322 |
+
x = 1
|
| 1323 |
+
for i in range(m):
|
| 1324 |
+
T[x] = i
|
| 1325 |
+
x = x * b % n
|
| 1326 |
+
z = pow(b, -m, n)
|
| 1327 |
+
x = a
|
| 1328 |
+
for i in range(m):
|
| 1329 |
+
if x in T:
|
| 1330 |
+
return i * m + T[x]
|
| 1331 |
+
x = x * z % n
|
| 1332 |
+
raise ValueError("Log does not exist")
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
|
| 1336 |
+
"""
|
| 1337 |
+
Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
|
| 1338 |
+
the base ``b`` modulo ``n``.
|
| 1339 |
+
|
| 1340 |
+
It is a randomized algorithm with the same expected running time as
|
| 1341 |
+
``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
|
| 1342 |
+
|
| 1343 |
+
Examples
|
| 1344 |
+
========
|
| 1345 |
+
|
| 1346 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
|
| 1347 |
+
>>> _discrete_log_pollard_rho(227, 3**7, 3)
|
| 1348 |
+
7
|
| 1349 |
+
|
| 1350 |
+
See Also
|
| 1351 |
+
========
|
| 1352 |
+
|
| 1353 |
+
discrete_log
|
| 1354 |
+
|
| 1355 |
+
References
|
| 1356 |
+
==========
|
| 1357 |
+
|
| 1358 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1359 |
+
Vanstone, S. A. (1997).
|
| 1360 |
+
"""
|
| 1361 |
+
a %= n
|
| 1362 |
+
b %= n
|
| 1363 |
+
|
| 1364 |
+
if order is None:
|
| 1365 |
+
order = n_order(b, n)
|
| 1366 |
+
randint = _randint(rseed)
|
| 1367 |
+
|
| 1368 |
+
for i in range(retries):
|
| 1369 |
+
aa = randint(1, order - 1)
|
| 1370 |
+
ba = randint(1, order - 1)
|
| 1371 |
+
xa = pow(b, aa, n) * pow(a, ba, n) % n
|
| 1372 |
+
|
| 1373 |
+
c = xa % 3
|
| 1374 |
+
if c == 0:
|
| 1375 |
+
xb = a * xa % n
|
| 1376 |
+
ab = aa
|
| 1377 |
+
bb = (ba + 1) % order
|
| 1378 |
+
elif c == 1:
|
| 1379 |
+
xb = xa * xa % n
|
| 1380 |
+
ab = (aa + aa) % order
|
| 1381 |
+
bb = (ba + ba) % order
|
| 1382 |
+
else:
|
| 1383 |
+
xb = b * xa % n
|
| 1384 |
+
ab = (aa + 1) % order
|
| 1385 |
+
bb = ba
|
| 1386 |
+
|
| 1387 |
+
for j in range(order):
|
| 1388 |
+
c = xa % 3
|
| 1389 |
+
if c == 0:
|
| 1390 |
+
xa = a * xa % n
|
| 1391 |
+
ba = (ba + 1) % order
|
| 1392 |
+
elif c == 1:
|
| 1393 |
+
xa = xa * xa % n
|
| 1394 |
+
aa = (aa + aa) % order
|
| 1395 |
+
ba = (ba + ba) % order
|
| 1396 |
+
else:
|
| 1397 |
+
xa = b * xa % n
|
| 1398 |
+
aa = (aa + 1) % order
|
| 1399 |
+
|
| 1400 |
+
c = xb % 3
|
| 1401 |
+
if c == 0:
|
| 1402 |
+
xb = a * xb % n
|
| 1403 |
+
bb = (bb + 1) % order
|
| 1404 |
+
elif c == 1:
|
| 1405 |
+
xb = xb * xb % n
|
| 1406 |
+
ab = (ab + ab) % order
|
| 1407 |
+
bb = (bb + bb) % order
|
| 1408 |
+
else:
|
| 1409 |
+
xb = b * xb % n
|
| 1410 |
+
ab = (ab + 1) % order
|
| 1411 |
+
|
| 1412 |
+
c = xb % 3
|
| 1413 |
+
if c == 0:
|
| 1414 |
+
xb = a * xb % n
|
| 1415 |
+
bb = (bb + 1) % order
|
| 1416 |
+
elif c == 1:
|
| 1417 |
+
xb = xb * xb % n
|
| 1418 |
+
ab = (ab + ab) % order
|
| 1419 |
+
bb = (bb + bb) % order
|
| 1420 |
+
else:
|
| 1421 |
+
xb = b * xb % n
|
| 1422 |
+
ab = (ab + 1) % order
|
| 1423 |
+
|
| 1424 |
+
if xa == xb:
|
| 1425 |
+
r = (ba - bb) % order
|
| 1426 |
+
try:
|
| 1427 |
+
e = invert(r, order) * (ab - aa) % order
|
| 1428 |
+
if (pow(b, e, n) - a) % n == 0:
|
| 1429 |
+
return e
|
| 1430 |
+
except ZeroDivisionError:
|
| 1431 |
+
pass
|
| 1432 |
+
break
|
| 1433 |
+
raise ValueError("Pollard's Rho failed to find logarithm")
|
| 1434 |
+
|
| 1435 |
+
|
| 1436 |
+
def _discrete_log_is_smooth(n: int, factorbase: list):
|
| 1437 |
+
"""Try to factor n with respect to a given factorbase.
|
| 1438 |
+
Upon success a list of exponents with repect to the factorbase is returned.
|
| 1439 |
+
Otherwise None."""
|
| 1440 |
+
factors = [0]*len(factorbase)
|
| 1441 |
+
for i, p in enumerate(factorbase):
|
| 1442 |
+
while n % p == 0: # divide by p as many times as possible
|
| 1443 |
+
factors[i] += 1
|
| 1444 |
+
n = n // p
|
| 1445 |
+
if n != 1:
|
| 1446 |
+
return None # the number factors if at the end nothing is left
|
| 1447 |
+
return factors
|
| 1448 |
+
|
| 1449 |
+
|
| 1450 |
+
def _discrete_log_index_calculus(n, a, b, order, rseed=None):
|
| 1451 |
+
"""
|
| 1452 |
+
Index Calculus algorithm for computing the discrete logarithm of ``a`` to
|
| 1453 |
+
the base ``b`` modulo ``n``.
|
| 1454 |
+
|
| 1455 |
+
The group order must be given and prime. It is not suitable for small orders
|
| 1456 |
+
and the algorithm might fail to find a solution in such situations.
|
| 1457 |
+
|
| 1458 |
+
Examples
|
| 1459 |
+
========
|
| 1460 |
+
|
| 1461 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_index_calculus
|
| 1462 |
+
>>> _discrete_log_index_calculus(24570203447, 23859756228, 2, 12285101723)
|
| 1463 |
+
4519867240
|
| 1464 |
+
|
| 1465 |
+
See Also
|
| 1466 |
+
========
|
| 1467 |
+
|
| 1468 |
+
discrete_log
|
| 1469 |
+
|
| 1470 |
+
References
|
| 1471 |
+
==========
|
| 1472 |
+
|
| 1473 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1474 |
+
Vanstone, S. A. (1997).
|
| 1475 |
+
"""
|
| 1476 |
+
randint = _randint(rseed)
|
| 1477 |
+
from math import sqrt, exp, log
|
| 1478 |
+
a %= n
|
| 1479 |
+
b %= n
|
| 1480 |
+
# assert isprime(order), "The order of the base must be prime."
|
| 1481 |
+
# First choose a heuristic the bound B for the factorbase.
|
| 1482 |
+
# We have added an extra term to the asymptotic value which
|
| 1483 |
+
# is closer to the theoretical optimum for n up to 2^70.
|
| 1484 |
+
B = int(exp(0.5 * sqrt( log(n) * log(log(n)) )*( 1 + 1/log(log(n)) )))
|
| 1485 |
+
max = 5 * B * B # expected number of trys to find a relation
|
| 1486 |
+
factorbase = list(primerange(B)) # compute the factorbase
|
| 1487 |
+
lf = len(factorbase) # length of the factorbase
|
| 1488 |
+
ordermo = order-1
|
| 1489 |
+
abx = a
|
| 1490 |
+
for x in range(order):
|
| 1491 |
+
if abx == 1:
|
| 1492 |
+
return (order - x) % order
|
| 1493 |
+
relationa = _discrete_log_is_smooth(abx, factorbase)
|
| 1494 |
+
if relationa:
|
| 1495 |
+
relationa = [r % order for r in relationa] + [x]
|
| 1496 |
+
break
|
| 1497 |
+
abx = abx * b % n # abx = a*pow(b, x, n) % n
|
| 1498 |
+
|
| 1499 |
+
else:
|
| 1500 |
+
raise ValueError("Index Calculus failed")
|
| 1501 |
+
|
| 1502 |
+
relations = [None] * lf
|
| 1503 |
+
k = 1 # number of relations found
|
| 1504 |
+
kk = 0
|
| 1505 |
+
while k < 3 * lf and kk < max: # find relations for all primes in our factor base
|
| 1506 |
+
x = randint(1,ordermo)
|
| 1507 |
+
relation = _discrete_log_is_smooth(pow(b,x,n), factorbase)
|
| 1508 |
+
if relation is None:
|
| 1509 |
+
kk += 1
|
| 1510 |
+
continue
|
| 1511 |
+
k += 1
|
| 1512 |
+
kk = 0
|
| 1513 |
+
relation += [ x ]
|
| 1514 |
+
index = lf # determine the index of the first nonzero entry
|
| 1515 |
+
for i in range(lf):
|
| 1516 |
+
ri = relation[i] % order
|
| 1517 |
+
if ri> 0 and relations[i] is not None: # make this entry zero if we can
|
| 1518 |
+
for j in range(lf+1):
|
| 1519 |
+
relation[j] = (relation[j] - ri*relations[i][j]) % order
|
| 1520 |
+
else:
|
| 1521 |
+
relation[i] = ri
|
| 1522 |
+
if relation[i] > 0 and index == lf: # is this the index of the first nonzero entry?
|
| 1523 |
+
index = i
|
| 1524 |
+
if index == lf or relations[index] is not None: # the relation contains no new information
|
| 1525 |
+
continue
|
| 1526 |
+
# the relation contains new information
|
| 1527 |
+
rinv = pow(relation[index],-1,order) # normalize the first nonzero entry
|
| 1528 |
+
for j in range(index,lf+1):
|
| 1529 |
+
relation[j] = rinv * relation[j] % order
|
| 1530 |
+
relations[index] = relation
|
| 1531 |
+
for i in range(lf): # subtract the new relation from the one for a
|
| 1532 |
+
if relationa[i] > 0 and relations[i] is not None:
|
| 1533 |
+
rbi = relationa[i]
|
| 1534 |
+
for j in range(lf+1):
|
| 1535 |
+
relationa[j] = (relationa[j] - rbi*relations[i][j]) % order
|
| 1536 |
+
if relationa[i] > 0: # the index of the first nonzero entry
|
| 1537 |
+
break # we do not need to reduce further at this point
|
| 1538 |
+
else: # all unkowns are gone
|
| 1539 |
+
#print(f"Success after {k} relations out of {lf}")
|
| 1540 |
+
x = (order -relationa[lf]) % order
|
| 1541 |
+
if pow(b,x,n) == a:
|
| 1542 |
+
return x
|
| 1543 |
+
raise ValueError("Index Calculus failed")
|
| 1544 |
+
raise ValueError("Index Calculus failed")
|
| 1545 |
+
|
| 1546 |
+
|
| 1547 |
+
def _discrete_log_pohlig_hellman(n, a, b, order=None, order_factors=None):
|
| 1548 |
+
"""
|
| 1549 |
+
Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
|
| 1550 |
+
the base ``b`` modulo ``n``.
|
| 1551 |
+
|
| 1552 |
+
In order to compute the discrete logarithm, the algorithm takes advantage
|
| 1553 |
+
of the factorization of the group order. It is more efficient when the
|
| 1554 |
+
group order factors into many small primes.
|
| 1555 |
+
|
| 1556 |
+
Examples
|
| 1557 |
+
========
|
| 1558 |
+
|
| 1559 |
+
>>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
|
| 1560 |
+
>>> _discrete_log_pohlig_hellman(251, 210, 71)
|
| 1561 |
+
197
|
| 1562 |
+
|
| 1563 |
+
See Also
|
| 1564 |
+
========
|
| 1565 |
+
|
| 1566 |
+
discrete_log
|
| 1567 |
+
|
| 1568 |
+
References
|
| 1569 |
+
==========
|
| 1570 |
+
|
| 1571 |
+
.. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1572 |
+
Vanstone, S. A. (1997).
|
| 1573 |
+
"""
|
| 1574 |
+
from .modular import crt
|
| 1575 |
+
a %= n
|
| 1576 |
+
b %= n
|
| 1577 |
+
|
| 1578 |
+
if order is None:
|
| 1579 |
+
order = n_order(b, n)
|
| 1580 |
+
if order_factors is None:
|
| 1581 |
+
order_factors = factorint(order)
|
| 1582 |
+
l = [0] * len(order_factors)
|
| 1583 |
+
|
| 1584 |
+
for i, (pi, ri) in enumerate(order_factors.items()):
|
| 1585 |
+
for j in range(ri):
|
| 1586 |
+
aj = pow(a * pow(b, -l[i], n), order // pi**(j + 1), n)
|
| 1587 |
+
bj = pow(b, order // pi, n)
|
| 1588 |
+
cj = discrete_log(n, aj, bj, pi, True)
|
| 1589 |
+
l[i] += cj * pi**j
|
| 1590 |
+
|
| 1591 |
+
d, _ = crt([pi**ri for pi, ri in order_factors.items()], l)
|
| 1592 |
+
return d
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
def discrete_log(n, a, b, order=None, prime_order=None):
|
| 1596 |
+
"""
|
| 1597 |
+
Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
|
| 1598 |
+
|
| 1599 |
+
This is a recursive function to reduce the discrete logarithm problem in
|
| 1600 |
+
cyclic groups of composite order to the problem in cyclic groups of prime
|
| 1601 |
+
order.
|
| 1602 |
+
|
| 1603 |
+
It employs different algorithms depending on the problem (subgroup order
|
| 1604 |
+
size, prime order or not):
|
| 1605 |
+
|
| 1606 |
+
* Trial multiplication
|
| 1607 |
+
* Baby-step giant-step
|
| 1608 |
+
* Pollard's Rho
|
| 1609 |
+
* Index Calculus
|
| 1610 |
+
* Pohlig-Hellman
|
| 1611 |
+
|
| 1612 |
+
Examples
|
| 1613 |
+
========
|
| 1614 |
+
|
| 1615 |
+
>>> from sympy.ntheory import discrete_log
|
| 1616 |
+
>>> discrete_log(41, 15, 7)
|
| 1617 |
+
3
|
| 1618 |
+
|
| 1619 |
+
References
|
| 1620 |
+
==========
|
| 1621 |
+
|
| 1622 |
+
.. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
|
| 1623 |
+
.. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
|
| 1624 |
+
Vanstone, S. A. (1997).
|
| 1625 |
+
|
| 1626 |
+
"""
|
| 1627 |
+
from math import sqrt, log
|
| 1628 |
+
n, a, b = as_int(n), as_int(a), as_int(b)
|
| 1629 |
+
if order is None:
|
| 1630 |
+
# Compute the order and its factoring in one pass
|
| 1631 |
+
# order = totient(n), factors = factorint(order)
|
| 1632 |
+
factors = {}
|
| 1633 |
+
for px, kx in factorint(n).items():
|
| 1634 |
+
if kx > 1:
|
| 1635 |
+
if px in factors:
|
| 1636 |
+
factors[px] += kx - 1
|
| 1637 |
+
else:
|
| 1638 |
+
factors[px] = kx - 1
|
| 1639 |
+
for py, ky in factorint(px - 1).items():
|
| 1640 |
+
if py in factors:
|
| 1641 |
+
factors[py] += ky
|
| 1642 |
+
else:
|
| 1643 |
+
factors[py] = ky
|
| 1644 |
+
order = 1
|
| 1645 |
+
for px, kx in factors.items():
|
| 1646 |
+
order *= px**kx
|
| 1647 |
+
# Now the `order` is the order of the group and factors = factorint(order)
|
| 1648 |
+
# The order of `b` divides the order of the group.
|
| 1649 |
+
order_factors = {}
|
| 1650 |
+
for p, e in factors.items():
|
| 1651 |
+
i = 0
|
| 1652 |
+
for _ in range(e):
|
| 1653 |
+
if pow(b, order // p, n) == 1:
|
| 1654 |
+
order //= p
|
| 1655 |
+
i += 1
|
| 1656 |
+
else:
|
| 1657 |
+
break
|
| 1658 |
+
if i < e:
|
| 1659 |
+
order_factors[p] = e - i
|
| 1660 |
+
|
| 1661 |
+
if prime_order is None:
|
| 1662 |
+
prime_order = isprime(order)
|
| 1663 |
+
|
| 1664 |
+
if order < 1000:
|
| 1665 |
+
return _discrete_log_trial_mul(n, a, b, order)
|
| 1666 |
+
elif prime_order:
|
| 1667 |
+
# Shanks and Pollard rho are O(sqrt(order)) while index calculus is O(exp(2*sqrt(log(n)log(log(n)))))
|
| 1668 |
+
# we compare the expected running times to determine the algorithmus which is expected to be faster
|
| 1669 |
+
if 4*sqrt(log(n)*log(log(n))) < log(order) - 10: # the number 10 was determined experimental
|
| 1670 |
+
return _discrete_log_index_calculus(n, a, b, order)
|
| 1671 |
+
elif order < 1000000000000:
|
| 1672 |
+
# Shanks seems typically faster, but uses O(sqrt(order)) memory
|
| 1673 |
+
return _discrete_log_shanks_steps(n, a, b, order)
|
| 1674 |
+
return _discrete_log_pollard_rho(n, a, b, order)
|
| 1675 |
+
|
| 1676 |
+
return _discrete_log_pohlig_hellman(n, a, b, order, order_factors)
|
| 1677 |
+
|
| 1678 |
+
|
| 1679 |
+
|
| 1680 |
+
def quadratic_congruence(a, b, c, n):
|
| 1681 |
+
r"""
|
| 1682 |
+
Find the solutions to `a x^2 + b x + c \equiv 0 \pmod{n}`.
|
| 1683 |
+
|
| 1684 |
+
Parameters
|
| 1685 |
+
==========
|
| 1686 |
+
|
| 1687 |
+
a : int
|
| 1688 |
+
b : int
|
| 1689 |
+
c : int
|
| 1690 |
+
n : int
|
| 1691 |
+
A positive integer.
|
| 1692 |
+
|
| 1693 |
+
Returns
|
| 1694 |
+
=======
|
| 1695 |
+
|
| 1696 |
+
list[int] :
|
| 1697 |
+
A sorted list of solutions. If no solution exists, ``[]``.
|
| 1698 |
+
|
| 1699 |
+
Examples
|
| 1700 |
+
========
|
| 1701 |
+
|
| 1702 |
+
>>> from sympy.ntheory.residue_ntheory import quadratic_congruence
|
| 1703 |
+
>>> quadratic_congruence(2, 5, 3, 7) # 2x^2 + 5x + 3 = 0 (mod 7)
|
| 1704 |
+
[2, 6]
|
| 1705 |
+
>>> quadratic_congruence(8, 6, 4, 15) # No solution
|
| 1706 |
+
[]
|
| 1707 |
+
|
| 1708 |
+
See Also
|
| 1709 |
+
========
|
| 1710 |
+
|
| 1711 |
+
polynomial_congruence : Solve the polynomial congruence
|
| 1712 |
+
|
| 1713 |
+
"""
|
| 1714 |
+
a = as_int(a)
|
| 1715 |
+
b = as_int(b)
|
| 1716 |
+
c = as_int(c)
|
| 1717 |
+
n = as_int(n)
|
| 1718 |
+
if n <= 1:
|
| 1719 |
+
raise ValueError("n should be an integer greater than 1")
|
| 1720 |
+
a %= n
|
| 1721 |
+
b %= n
|
| 1722 |
+
c %= n
|
| 1723 |
+
|
| 1724 |
+
if a == 0:
|
| 1725 |
+
return linear_congruence(b, -c, n)
|
| 1726 |
+
if n == 2:
|
| 1727 |
+
# assert a == 1
|
| 1728 |
+
roots = []
|
| 1729 |
+
if c == 0:
|
| 1730 |
+
roots.append(0)
|
| 1731 |
+
if (b + c) % 2:
|
| 1732 |
+
roots.append(1)
|
| 1733 |
+
return roots
|
| 1734 |
+
if gcd(2*a, n) == 1:
|
| 1735 |
+
inv_a = invert(a, n)
|
| 1736 |
+
b *= inv_a
|
| 1737 |
+
c *= inv_a
|
| 1738 |
+
if b % 2:
|
| 1739 |
+
b += n
|
| 1740 |
+
b >>= 1
|
| 1741 |
+
return sorted((i - b) % n for i in sqrt_mod_iter(b**2 - c, n))
|
| 1742 |
+
res = set()
|
| 1743 |
+
for i in sqrt_mod_iter(b**2 - 4*a*c, 4*a*n):
|
| 1744 |
+
res.update(j % n for j in linear_congruence(2*a, i - b, 4*a*n))
|
| 1745 |
+
return sorted(res)
|
| 1746 |
+
|
| 1747 |
+
|
| 1748 |
+
def _valid_expr(expr):
|
| 1749 |
+
"""
|
| 1750 |
+
return coefficients of expr if it is a univariate polynomial
|
| 1751 |
+
with integer coefficients else raise a ValueError.
|
| 1752 |
+
"""
|
| 1753 |
+
|
| 1754 |
+
if not expr.is_polynomial():
|
| 1755 |
+
raise ValueError("The expression should be a polynomial")
|
| 1756 |
+
polynomial = Poly(expr)
|
| 1757 |
+
if not polynomial.is_univariate:
|
| 1758 |
+
raise ValueError("The expression should be univariate")
|
| 1759 |
+
if not polynomial.domain == ZZ:
|
| 1760 |
+
raise ValueError("The expression should should have integer coefficients")
|
| 1761 |
+
return polynomial.all_coeffs()
|
| 1762 |
+
|
| 1763 |
+
|
| 1764 |
+
def polynomial_congruence(expr, m):
|
| 1765 |
+
"""
|
| 1766 |
+
Find the solutions to a polynomial congruence equation modulo m.
|
| 1767 |
+
|
| 1768 |
+
Parameters
|
| 1769 |
+
==========
|
| 1770 |
+
|
| 1771 |
+
expr : integer coefficient polynomial
|
| 1772 |
+
m : positive integer
|
| 1773 |
+
|
| 1774 |
+
Examples
|
| 1775 |
+
========
|
| 1776 |
+
|
| 1777 |
+
>>> from sympy.ntheory import polynomial_congruence
|
| 1778 |
+
>>> from sympy.abc import x
|
| 1779 |
+
>>> expr = x**6 - 2*x**5 -35
|
| 1780 |
+
>>> polynomial_congruence(expr, 6125)
|
| 1781 |
+
[3257]
|
| 1782 |
+
|
| 1783 |
+
See Also
|
| 1784 |
+
========
|
| 1785 |
+
|
| 1786 |
+
sympy.polys.galoistools.gf_csolve : low level solving routine used by this routine
|
| 1787 |
+
|
| 1788 |
+
"""
|
| 1789 |
+
coefficients = _valid_expr(expr)
|
| 1790 |
+
coefficients = [num % m for num in coefficients]
|
| 1791 |
+
rank = len(coefficients)
|
| 1792 |
+
if rank == 3:
|
| 1793 |
+
return quadratic_congruence(*coefficients, m)
|
| 1794 |
+
if rank == 2:
|
| 1795 |
+
return quadratic_congruence(0, *coefficients, m)
|
| 1796 |
+
if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients):
|
| 1797 |
+
return nthroot_mod(-coefficients[-1], rank - 1, m, True)
|
| 1798 |
+
return gf_csolve(coefficients, m)
|
| 1799 |
+
|
| 1800 |
+
|
| 1801 |
+
def binomial_mod(n, m, k):
|
| 1802 |
+
"""Compute ``binomial(n, m) % k``.
|
| 1803 |
+
|
| 1804 |
+
Explanation
|
| 1805 |
+
===========
|
| 1806 |
+
|
| 1807 |
+
Returns ``binomial(n, m) % k`` using a generalization of Lucas'
|
| 1808 |
+
Theorem for prime powers given by Granville [1]_, in conjunction with
|
| 1809 |
+
the Chinese Remainder Theorem. The residue for each prime power
|
| 1810 |
+
is calculated in time O(log^2(n) + q^4*log(n)log(p) + q^4*p*log^3(p)).
|
| 1811 |
+
|
| 1812 |
+
Parameters
|
| 1813 |
+
==========
|
| 1814 |
+
|
| 1815 |
+
n : an integer
|
| 1816 |
+
m : an integer
|
| 1817 |
+
k : a positive integer
|
| 1818 |
+
|
| 1819 |
+
Examples
|
| 1820 |
+
========
|
| 1821 |
+
|
| 1822 |
+
>>> from sympy.ntheory.residue_ntheory import binomial_mod
|
| 1823 |
+
>>> binomial_mod(10, 2, 6) # binomial(10, 2) = 45
|
| 1824 |
+
3
|
| 1825 |
+
>>> binomial_mod(17, 9, 10) # binomial(17, 9) = 24310
|
| 1826 |
+
0
|
| 1827 |
+
|
| 1828 |
+
References
|
| 1829 |
+
==========
|
| 1830 |
+
|
| 1831 |
+
.. [1] Binomial coefficients modulo prime powers, Andrew Granville,
|
| 1832 |
+
Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
|
| 1833 |
+
"""
|
| 1834 |
+
if k < 1: raise ValueError('k is required to be positive')
|
| 1835 |
+
# We decompose q into a product of prime powers and apply
|
| 1836 |
+
# the generalization of Lucas' Theorem given by Granville
|
| 1837 |
+
# to obtain binomial(n, k) mod p^e, and then use the Chinese
|
| 1838 |
+
# Remainder Theorem to obtain the result mod q
|
| 1839 |
+
if n < 0 or m < 0 or m > n: return 0
|
| 1840 |
+
factorisation = factorint(k)
|
| 1841 |
+
residues = [_binomial_mod_prime_power(n, m, p, e) for p, e in factorisation.items()]
|
| 1842 |
+
return crt([p**pw for p, pw in factorisation.items()], residues, check=False)[0]
|
| 1843 |
+
|
| 1844 |
+
|
| 1845 |
+
def _binomial_mod_prime_power(n, m, p, q):
|
| 1846 |
+
"""Compute ``binomial(n, m) % p**q`` for a prime ``p``.
|
| 1847 |
+
|
| 1848 |
+
Parameters
|
| 1849 |
+
==========
|
| 1850 |
+
|
| 1851 |
+
n : positive integer
|
| 1852 |
+
m : a nonnegative integer
|
| 1853 |
+
p : a prime
|
| 1854 |
+
q : a positive integer (the prime exponent)
|
| 1855 |
+
|
| 1856 |
+
Examples
|
| 1857 |
+
========
|
| 1858 |
+
|
| 1859 |
+
>>> from sympy.ntheory.residue_ntheory import _binomial_mod_prime_power
|
| 1860 |
+
>>> _binomial_mod_prime_power(10, 2, 3, 2) # binomial(10, 2) = 45
|
| 1861 |
+
0
|
| 1862 |
+
>>> _binomial_mod_prime_power(17, 9, 2, 4) # binomial(17, 9) = 24310
|
| 1863 |
+
6
|
| 1864 |
+
|
| 1865 |
+
References
|
| 1866 |
+
==========
|
| 1867 |
+
|
| 1868 |
+
.. [1] Binomial coefficients modulo prime powers, Andrew Granville,
|
| 1869 |
+
Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
|
| 1870 |
+
"""
|
| 1871 |
+
# Function/variable naming within this function follows Ref.[1]
|
| 1872 |
+
# n!_p will be used to denote the product of integers <= n not divisible by
|
| 1873 |
+
# p, with binomial(n, m)_p the same as binomial(n, m), but defined using
|
| 1874 |
+
# n!_p in place of n!
|
| 1875 |
+
modulo = pow(p, q)
|
| 1876 |
+
|
| 1877 |
+
def up_factorial(u):
|
| 1878 |
+
"""Compute (u*p)!_p modulo p^q."""
|
| 1879 |
+
r = q // 2
|
| 1880 |
+
fac = prod = 1
|
| 1881 |
+
if r == 1 and p == 2 or 2*r + 1 in (p, p*p):
|
| 1882 |
+
if q % 2 == 1: r += 1
|
| 1883 |
+
modulo, div = pow(p, 2*r), pow(p, 2*r - q)
|
| 1884 |
+
else:
|
| 1885 |
+
modulo, div = pow(p, 2*r + 1), pow(p, (2*r + 1) - q)
|
| 1886 |
+
for j in range(1, r + 1):
|
| 1887 |
+
for mul in range((j - 1)*p + 1, j*p): # ignore jp itself
|
| 1888 |
+
fac *= mul
|
| 1889 |
+
fac %= modulo
|
| 1890 |
+
bj_ = bj(u, j, r)
|
| 1891 |
+
prod *= pow(fac, bj_, modulo)
|
| 1892 |
+
prod %= modulo
|
| 1893 |
+
if p == 2:
|
| 1894 |
+
sm = u // 2
|
| 1895 |
+
for j in range(1, r + 1): sm += j//2 * bj(u, j, r)
|
| 1896 |
+
if sm % 2 == 1: prod *= -1
|
| 1897 |
+
prod %= modulo//div
|
| 1898 |
+
return prod % modulo
|
| 1899 |
+
|
| 1900 |
+
def bj(u, j, r):
|
| 1901 |
+
"""Compute the exponent of (j*p)!_p in the calculation of (u*p)!_p."""
|
| 1902 |
+
prod = u
|
| 1903 |
+
for i in range(1, r + 1):
|
| 1904 |
+
if i != j: prod *= u*u - i*i
|
| 1905 |
+
for i in range(1, r + 1):
|
| 1906 |
+
if i != j: prod //= j*j - i*i
|
| 1907 |
+
return prod // j
|
| 1908 |
+
|
| 1909 |
+
def up_plus_v_binom(u, v):
|
| 1910 |
+
"""Compute binomial(u*p + v, v)_p modulo p^q."""
|
| 1911 |
+
prod = 1
|
| 1912 |
+
div = invert(factorial(v), modulo)
|
| 1913 |
+
for j in range(1, q):
|
| 1914 |
+
b = div
|
| 1915 |
+
for v_ in range(j*p + 1, j*p + v + 1):
|
| 1916 |
+
b *= v_
|
| 1917 |
+
b %= modulo
|
| 1918 |
+
aj = u
|
| 1919 |
+
for i in range(1, q):
|
| 1920 |
+
if i != j: aj *= u - i
|
| 1921 |
+
for i in range(1, q):
|
| 1922 |
+
if i != j: aj //= j - i
|
| 1923 |
+
aj //= j
|
| 1924 |
+
prod *= pow(b, aj, modulo)
|
| 1925 |
+
prod %= modulo
|
| 1926 |
+
return prod
|
| 1927 |
+
|
| 1928 |
+
@recurrence_memo([1])
|
| 1929 |
+
def factorial(v, prev):
|
| 1930 |
+
"""Compute v! modulo p^q."""
|
| 1931 |
+
return v*prev[-1] % modulo
|
| 1932 |
+
|
| 1933 |
+
def factorial_p(n):
|
| 1934 |
+
"""Compute n!_p modulo p^q."""
|
| 1935 |
+
u, v = divmod(n, p)
|
| 1936 |
+
return (factorial(v) * up_factorial(u) * up_plus_v_binom(u, v)) % modulo
|
| 1937 |
+
|
| 1938 |
+
prod = 1
|
| 1939 |
+
Nj, Mj, Rj = n, m, n - m
|
| 1940 |
+
# e0 will be the p-adic valuation of binomial(n, m) at p
|
| 1941 |
+
e0 = carry = eq_1 = j = 0
|
| 1942 |
+
while Nj:
|
| 1943 |
+
numerator = factorial_p(Nj % modulo)
|
| 1944 |
+
denominator = factorial_p(Mj % modulo) * factorial_p(Rj % modulo) % modulo
|
| 1945 |
+
Nj, (Mj, mj), (Rj, rj) = Nj//p, divmod(Mj, p), divmod(Rj, p)
|
| 1946 |
+
carry = (mj + rj + carry) // p
|
| 1947 |
+
e0 += carry
|
| 1948 |
+
if j >= q - 1: eq_1 += carry
|
| 1949 |
+
prod *= numerator * invert(denominator, modulo)
|
| 1950 |
+
prod %= modulo
|
| 1951 |
+
j += 1
|
| 1952 |
+
|
| 1953 |
+
mul = pow(1 if p == 2 and q >= 3 else -1, eq_1, modulo)
|
| 1954 |
+
return (pow(p, e0, modulo) * mul * prod) % modulo
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py
ADDED
|
File without changes
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc
ADDED
|
Binary file (2.79 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.random import randint
|
| 2 |
+
|
| 3 |
+
from sympy.ntheory.bbp_pi import pi_hex_digits
|
| 4 |
+
from sympy.testing.pytest import raises
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
|
| 8 |
+
# There are actually 8336 listed there; with the prepended 3 there are 8337
|
| 9 |
+
# below
|
| 10 |
+
dig=''.join('''
|
| 11 |
+
3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
|
| 12 |
+
77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
|
| 13 |
+
ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
|
| 14 |
+
16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
|
| 15 |
+
b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
|
| 16 |
+
3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
|
| 17 |
+
b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
|
| 18 |
+
1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
|
| 19 |
+
91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
|
| 20 |
+
392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
|
| 21 |
+
68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
|
| 22 |
+
888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
|
| 23 |
+
061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
|
| 24 |
+
f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
|
| 25 |
+
b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
|
| 26 |
+
b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
|
| 27 |
+
cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
|
| 28 |
+
829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
|
| 29 |
+
c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
|
| 30 |
+
90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
|
| 31 |
+
98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
|
| 32 |
+
1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
|
| 33 |
+
e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
|
| 34 |
+
77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
|
| 35 |
+
5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
|
| 36 |
+
c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
|
| 37 |
+
e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
|
| 38 |
+
6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
|
| 39 |
+
7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
|
| 40 |
+
3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
|
| 41 |
+
266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
|
| 42 |
+
373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
|
| 43 |
+
b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
|
| 44 |
+
a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
|
| 45 |
+
086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
|
| 46 |
+
2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
|
| 47 |
+
fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
|
| 48 |
+
dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
|
| 49 |
+
fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
|
| 50 |
+
0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
|
| 51 |
+
3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
|
| 52 |
+
28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
|
| 53 |
+
70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
|
| 54 |
+
14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
|
| 55 |
+
b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
|
| 56 |
+
810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
|
| 57 |
+
548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
|
| 58 |
+
e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
|
| 59 |
+
c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
|
| 60 |
+
85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
|
| 61 |
+
41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
|
| 62 |
+
35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
|
| 63 |
+
cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
|
| 64 |
+
f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
|
| 65 |
+
6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
|
| 66 |
+
45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
|
| 67 |
+
f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
|
| 68 |
+
b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
|
| 69 |
+
5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
|
| 70 |
+
2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
|
| 71 |
+
f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
|
| 72 |
+
dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
|
| 73 |
+
60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
|
| 74 |
+
2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
|
| 75 |
+
fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
|
| 76 |
+
0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
|
| 77 |
+
9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
|
| 78 |
+
2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
|
| 79 |
+
fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
|
| 80 |
+
fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
|
| 81 |
+
71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
|
| 82 |
+
c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
|
| 83 |
+
708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
|
| 84 |
+
33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
|
| 85 |
+
fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
|
| 86 |
+
b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
|
| 87 |
+
deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
|
| 88 |
+
fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
|
| 89 |
+
c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
|
| 90 |
+
1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
|
| 91 |
+
45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
|
| 92 |
+
c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
|
| 93 |
+
f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
|
| 94 |
+
e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
|
| 95 |
+
972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
|
| 96 |
+
4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
|
| 97 |
+
55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
|
| 98 |
+
2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
|
| 99 |
+
f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
|
| 100 |
+
32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
|
| 101 |
+
dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
|
| 102 |
+
d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
|
| 103 |
+
57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
|
| 104 |
+
486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
|
| 105 |
+
4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
|
| 106 |
+
380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
|
| 107 |
+
2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
|
| 108 |
+
42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
|
| 109 |
+
8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
|
| 110 |
+
6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
|
| 111 |
+
b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
|
| 112 |
+
9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
|
| 113 |
+
d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
|
| 114 |
+
7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
|
| 115 |
+
5b578fdfe33ac372e6'''.split())
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_hex_pi_nth_digits():
|
| 119 |
+
assert pi_hex_digits(0) == '3243f6a8885a30'
|
| 120 |
+
assert pi_hex_digits(1) == '243f6a8885a308'
|
| 121 |
+
assert pi_hex_digits(10000) == '68ac8fcfb8016c'
|
| 122 |
+
assert pi_hex_digits(13) == '08d313198a2e03'
|
| 123 |
+
assert pi_hex_digits(0, 3) == '324'
|
| 124 |
+
assert pi_hex_digits(0, 0) == ''
|
| 125 |
+
raises(ValueError, lambda: pi_hex_digits(-1))
|
| 126 |
+
raises(ValueError, lambda: pi_hex_digits(0, -1))
|
| 127 |
+
raises(ValueError, lambda: pi_hex_digits(3.14))
|
| 128 |
+
|
| 129 |
+
# this will pick a random segment to compute every time
|
| 130 |
+
# it is run. If it ever fails, there is an error in the
|
| 131 |
+
# computation.
|
| 132 |
+
n = randint(0, len(dig))
|
| 133 |
+
prec = randint(0, len(dig) - n)
|
| 134 |
+
assert pi_hex_digits(n, prec) == dig[n: n + prec]
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.ntheory import count_digits, digits, is_palindromic
|
| 2 |
+
from sympy.core.intfunc import num_digits
|
| 3 |
+
|
| 4 |
+
from sympy.testing.pytest import raises
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_num_digits():
|
| 8 |
+
# depending on whether one rounds up or down or uses log or log10,
|
| 9 |
+
# one or more of these will fail if you don't check for the off-by
|
| 10 |
+
# one condition
|
| 11 |
+
assert num_digits(2, 2) == 2
|
| 12 |
+
assert num_digits(2**48 - 1, 2) == 48
|
| 13 |
+
assert num_digits(1000, 10) == 4
|
| 14 |
+
assert num_digits(125, 5) == 4
|
| 15 |
+
assert num_digits(100, 16) == 2
|
| 16 |
+
assert num_digits(-1000, 10) == 4
|
| 17 |
+
# if changes are made to the function, this structured test over
|
| 18 |
+
# this range will expose problems
|
| 19 |
+
for base in range(2, 100):
|
| 20 |
+
for e in range(1, 100):
|
| 21 |
+
n = base**e
|
| 22 |
+
assert num_digits(n, base) == e + 1
|
| 23 |
+
assert num_digits(n + 1, base) == e + 1
|
| 24 |
+
assert num_digits(n - 1, base) == e
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_digits():
|
| 28 |
+
assert all(digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
|
| 29 |
+
for n in range(20))
|
| 30 |
+
assert all(digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
|
| 31 |
+
for n in range(20))
|
| 32 |
+
assert all(digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
|
| 33 |
+
for n in range(20))
|
| 34 |
+
assert digits(2345, 34) == [34, 2, 0, 33]
|
| 35 |
+
assert digits(384753, 71) == [71, 1, 5, 23, 4]
|
| 36 |
+
assert digits(93409, 10) == [10, 9, 3, 4, 0, 9]
|
| 37 |
+
assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
|
| 38 |
+
assert digits(35, 10) == [10, 3, 5]
|
| 39 |
+
assert digits(35, 10, 3) == [10, 0, 3, 5]
|
| 40 |
+
assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5]
|
| 41 |
+
raises(ValueError, lambda: digits(2, 2, 1))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_count_digits():
|
| 45 |
+
assert count_digits(55, 2) == {1: 5, 0: 1}
|
| 46 |
+
assert count_digits(55, 10) == {5: 2}
|
| 47 |
+
n = count_digits(123)
|
| 48 |
+
assert n[4] == 0 and type(n[4]) is int
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_is_palindromic():
|
| 52 |
+
assert is_palindromic(-11)
|
| 53 |
+
assert is_palindromic(11)
|
| 54 |
+
assert is_palindromic(0o121, 8)
|
| 55 |
+
assert not is_palindromic(123)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_hypothesis.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from hypothesis import given
|
| 2 |
+
from hypothesis import strategies as st
|
| 3 |
+
from sympy import divisors
|
| 4 |
+
from sympy.functions.combinatorial.numbers import divisor_sigma, totient
|
| 5 |
+
from sympy.ntheory.primetest import is_square
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@given(n=st.integers(1, 10**10))
|
| 9 |
+
def test_tau_hypothesis(n):
|
| 10 |
+
div = divisors(n)
|
| 11 |
+
tau_n = len(div)
|
| 12 |
+
assert is_square(n) == (tau_n % 2 == 1)
|
| 13 |
+
sigmas = [divisor_sigma(i) for i in div]
|
| 14 |
+
totients = [totient(n // i) for i in div]
|
| 15 |
+
mul = [a * b for a, b in zip(sigmas, totients)]
|
| 16 |
+
assert n * tau_n == sum(mul)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@given(n=st.integers(1, 10**10))
|
| 20 |
+
def test_totient_hypothesis(n):
|
| 21 |
+
assert totient(n) <= n
|
| 22 |
+
div = divisors(n)
|
| 23 |
+
totients = [totient(i) for i in div]
|
| 24 |
+
assert n == sum(totients)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.66 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/aesaracode.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/c.cpython-310.pyc
ADDED
|
Binary file (26.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/codeprinter.cpython-310.pyc
ADDED
|
Binary file (31.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/conventions.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/cxx.cpython-310.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/defaults.cpython-310.pyc
ADDED
|
Binary file (284 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/dot.cpython-310.pyc
ADDED
|
Binary file (8.82 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/fortran.cpython-310.pyc
ADDED
|
Binary file (27.3 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/glsl.cpython-310.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/gtk.cpython-310.pyc
ADDED
|
Binary file (757 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/jscode.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/julia.cpython-310.pyc
ADDED
|
Binary file (23.3 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/lambdarepr.cpython-310.pyc
ADDED
|
Binary file (8.03 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/llvmjitcode.cpython-310.pyc
ADDED
|
Binary file (15.1 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/maple.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/mathematica.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/mathml.cpython-310.pyc
ADDED
|
Binary file (57.1 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/numpy.cpython-310.pyc
ADDED
|
Binary file (20.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/octave.cpython-310.pyc
ADDED
|
Binary file (26.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/precedence.cpython-310.pyc
ADDED
|
Binary file (3.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/preview.cpython-310.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/printer.cpython-310.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/pycode.cpython-310.pyc
ADDED
|
Binary file (27.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/python.cpython-310.pyc
ADDED
|
Binary file (2.62 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/rcode.cpython-310.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/repr.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/rust.cpython-310.pyc
ADDED
|
Binary file (17.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/smtlib.cpython-310.pyc
ADDED
|
Binary file (20.8 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/printing/__pycache__/str.cpython-310.pyc
ADDED
|
Binary file (39 kB). View file
|
|
|