diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..549b4b96cdce0ee4d31960e89cb9dc26af0e105d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/__init__.py @@ -0,0 +1,20 @@ +""" +Unified place for determining if external dependencies are installed or not. + +You should import all external modules using the import_module() function. + +For example + +>>> from sympy.external import import_module +>>> numpy = import_module('numpy') + +If the resulting library is not installed, or if the installed version +is less than a given minimum version, the function will return None. +Otherwise, it will return the library. See the docstring of +import_module() for more information. + +""" + +from sympy.external.importtools import import_module + +__all__ = ['import_module'] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2861a9631d32e3f022fda452ee39d1a9b0286c6 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ae736093ace164f9fbde80447b6aea812a88dd6 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b746138e479f0fe03cd9905539f7c42da63845 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec9d1b77f4583cbf2510cc381f69e53806fdcfda Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/gmpy.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/gmpy.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac0afada0aad63ac2e96bb5d7b32c7d325f848c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/gmpy.py @@ -0,0 +1,104 @@ +import os +from typing import Tuple as tTuple, Type + +import mpmath.libmp as mlib + +from sympy.external import import_module + +__all__ = [ + # GROUND_TYPES is either 'gmpy' or 'python' depending on which is used. If + # gmpy is installed then it will be used unless the environment variable + # SYMPY_GROUND_TYPES is set to something other than 'auto', 'gmpy', or + # 'gmpy2'. + 'GROUND_TYPES', + + # If HAS_GMPY is 0, no supported version of gmpy is available. Otherwise, + # HAS_GMPY will be 2 for gmpy2 if GROUND_TYPES is 'gmpy'. It used to be + # possible for HAS_GMPY to be 1 for gmpy but gmpy is no longer supported. + 'HAS_GMPY', + + # SYMPY_INTS is a tuple containing the base types for valid integer types. + # This is either (int,) or (int, type(mpz(0))) depending on GROUND_TYPES. + 'SYMPY_INTS', + + # MPQ is either gmpy.mpq or the Python equivalent from + # sympy.external.pythonmpq + 'MPQ', + + # MPZ is either gmpy.mpz or int. + 'MPZ', + + # Either the gmpy or the mpmath function + 'factorial', + + # isqrt from gmpy or mpmath + 'sqrt', +] + + +# +# SYMPY_GROUND_TYPES can be gmpy, gmpy2, python or auto +# +GROUND_TYPES = os.environ.get('SYMPY_GROUND_TYPES', 'auto').lower() + + +# +# Try to import gmpy2 by default. If gmpy or gmpy2 is specified in +# SYMPY_GROUND_TYPES then warn if gmpy2 is not found. In all cases there is a +# fallback based on pure Python int and PythonMPQ that should still work fine. +# +if GROUND_TYPES in ('auto', 'gmpy', 'gmpy2'): + + # Actually import gmpy2 + gmpy = import_module('gmpy2', min_module_version='2.0.0', + module_version_attr='version', module_version_attr_call_args=()) + + # Warn if user explicitly asked for gmpy but it isn't available. + if gmpy is None and GROUND_TYPES in ('gmpy', 'gmpy2'): + from warnings import warn + warn("gmpy library is not installed, switching to 'python' ground types") + +elif GROUND_TYPES == 'python': + + # The user asked for Python so ignore gmpy2 module. + gmpy = None + +else: + + # Invalid value for SYMPY_GROUND_TYPES. Ignore the gmpy2 module. + from warnings import warn + warn("SYMPY_GROUND_TYPES environment variable unrecognised. " + "Should be 'python', 'auto', 'gmpy', or 'gmpy2'") + gmpy = None + + +# +# At this point gmpy will be None if gmpy2 was not successfully imported or if +# the environment variable SYMPY_GROUND_TYPES was set to 'python' (or some +# unrecognised value). The two blocks below define the values exported by this +# module in each case. +# +SYMPY_INTS: tTuple[Type, ...] + +if gmpy is not None: + + HAS_GMPY = 2 + GROUND_TYPES = 'gmpy' + SYMPY_INTS = (int, type(gmpy.mpz(0))) + MPZ = gmpy.mpz + MPQ = gmpy.mpq + + factorial = gmpy.fac + sqrt = gmpy.isqrt + +else: + from .pythonmpq import PythonMPQ + + HAS_GMPY = 0 + GROUND_TYPES = 'python' + SYMPY_INTS = (int,) + MPZ = int + MPQ = PythonMPQ + + factorial = lambda x: int(mlib.ifac(x)) + sqrt = lambda x: int(mlib.isqrt(x)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/importtools.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/importtools.py new file mode 100644 index 0000000000000000000000000000000000000000..5008b3dd4634d3cee10744a0a92b1204051f07cc --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/importtools.py @@ -0,0 +1,187 @@ +"""Tools to assist importing optional external modules.""" + +import sys +import re + +# Override these in the module to change the default warning behavior. +# For example, you might set both to False before running the tests so that +# warnings are not printed to the console, or set both to True for debugging. + +WARN_NOT_INSTALLED = None # Default is False +WARN_OLD_VERSION = None # Default is True + + +def __sympy_debug(): + # helper function from sympy/__init__.py + # We don't just import SYMPY_DEBUG from that file because we don't want to + # import all of SymPy just to use this module. + import os + debug_str = os.getenv('SYMPY_DEBUG', 'False') + if debug_str in ('True', 'False'): + return eval(debug_str) + else: + raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % + debug_str) + +if __sympy_debug(): + WARN_OLD_VERSION = True + WARN_NOT_INSTALLED = True + + +_component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) + +def version_tuple(vstring): + # Parse a version string to a tuple e.g. '1.2' -> (1, 2) + # Simplified from distutils.version.LooseVersion which was deprecated in + # Python 3.10. + components = [] + for x in _component_re.split(vstring): + if x and x != '.': + try: + x = int(x) + except ValueError: + pass + components.append(x) + return tuple(components) + + +def import_module(module, min_module_version=None, min_python_version=None, + warn_not_installed=None, warn_old_version=None, + module_version_attr='__version__', module_version_attr_call_args=None, + import_kwargs={}, catch=()): + """ + Import and return a module if it is installed. + + If the module is not installed, it returns None. + + A minimum version for the module can be given as the keyword argument + min_module_version. This should be comparable against the module version. + By default, module.__version__ is used to get the module version. To + override this, set the module_version_attr keyword argument. If the + attribute of the module to get the version should be called (e.g., + module.version()), then set module_version_attr_call_args to the args such + that module.module_version_attr(*module_version_attr_call_args) returns the + module's version. + + If the module version is less than min_module_version using the Python < + comparison, None will be returned, even if the module is installed. You can + use this to keep from importing an incompatible older version of a module. + + You can also specify a minimum Python version by using the + min_python_version keyword argument. This should be comparable against + sys.version_info. + + If the keyword argument warn_not_installed is set to True, the function will + emit a UserWarning when the module is not installed. + + If the keyword argument warn_old_version is set to True, the function will + emit a UserWarning when the library is installed, but cannot be imported + because of the min_module_version or min_python_version options. + + Note that because of the way warnings are handled, a warning will be + emitted for each module only once. You can change the default warning + behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION + in sympy.external.importtools. By default, WARN_NOT_INSTALLED is False and + WARN_OLD_VERSION is True. + + This function uses __import__() to import the module. To pass additional + options to __import__(), use the import_kwargs keyword argument. For + example, to import a submodule A.B, you must pass a nonempty fromlist option + to __import__. See the docstring of __import__(). + + This catches ImportError to determine if the module is not installed. To + catch additional errors, pass them as a tuple to the catch keyword + argument. + + Examples + ======== + + >>> from sympy.external import import_module + + >>> numpy = import_module('numpy') + + >>> numpy = import_module('numpy', min_python_version=(2, 7), + ... warn_old_version=False) + + >>> numpy = import_module('numpy', min_module_version='1.5', + ... warn_old_version=False) # numpy.__version__ is a string + + >>> # gmpy does not have __version__, but it does have gmpy.version() + + >>> gmpy = import_module('gmpy', min_module_version='1.14', + ... module_version_attr='version', module_version_attr_call_args=(), + ... warn_old_version=False) + + >>> # To import a submodule, you must pass a nonempty fromlist to + >>> # __import__(). The values do not matter. + >>> p3 = import_module('mpl_toolkits.mplot3d', + ... import_kwargs={'fromlist':['something']}) + + >>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened + >>> matplotlib = import_module('matplotlib', + ... import_kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,)) + + """ + # keyword argument overrides default, and global variable overrides + # keyword argument. + warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None + else warn_old_version or True) + warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None + else warn_not_installed or False) + + import warnings + + # Check Python first so we don't waste time importing a module we can't use + if min_python_version: + if sys.version_info < min_python_version: + if warn_old_version: + warnings.warn("Python version is too old to use %s " + "(%s or newer required)" % ( + module, '.'.join(map(str, min_python_version))), + UserWarning, stacklevel=2) + return + + try: + mod = __import__(module, **import_kwargs) + + ## there's something funny about imports with matplotlib and py3k. doing + ## from matplotlib import collections + ## gives python's stdlib collections module. explicitly re-importing + ## the module fixes this. + from_list = import_kwargs.get('fromlist', ()) + for submod in from_list: + if submod == 'collections' and mod.__name__ == 'matplotlib': + __import__(module + '.' + submod) + except ImportError: + if warn_not_installed: + warnings.warn("%s module is not installed" % module, UserWarning, + stacklevel=2) + return + except catch as e: + if warn_not_installed: + warnings.warn( + "%s module could not be used (%s)" % (module, repr(e)), + stacklevel=2) + return + + if min_module_version: + modversion = getattr(mod, module_version_attr) + if module_version_attr_call_args is not None: + modversion = modversion(*module_version_attr_call_args) + if version_tuple(modversion) < version_tuple(min_module_version): + if warn_old_version: + # Attempt to create a pretty string version of the version + if isinstance(min_module_version, str): + verstr = min_module_version + elif isinstance(min_module_version, (tuple, list)): + verstr = '.'.join(map(str, min_module_version)) + else: + # Either don't know what this is. Hopefully + # it's something that has a nice str version, like an int. + verstr = str(min_module_version) + warnings.warn("%s version is too old to use " + "(%s or newer required)" % (module, verstr), + UserWarning, stacklevel=2) + return + + return mod diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/pythonmpq.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/pythonmpq.py new file mode 100644 index 0000000000000000000000000000000000000000..b8efd18a40a75b8a4f4de444b0c10d6347dbca6a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/pythonmpq.py @@ -0,0 +1,341 @@ +""" +PythonMPQ: Rational number type based on Python integers. + +This class is intended as a pure Python fallback for when gmpy2 is not +installed. If gmpy2 is installed then its mpq type will be used instead. The +mpq type is around 20x faster. We could just use the stdlib Fraction class +here but that is slower: + + from fractions import Fraction + from sympy.external.pythonmpq import PythonMPQ + nums = range(1000) + dens = range(5, 1005) + rats = [Fraction(n, d) for n, d in zip(nums, dens)] + sum(rats) # <--- 24 milliseconds + rats = [PythonMPQ(n, d) for n, d in zip(nums, dens)] + sum(rats) # <--- 7 milliseconds + +Both mpq and Fraction have some awkward features like the behaviour of +division with // and %: + + >>> from fractions import Fraction + >>> Fraction(2, 3) % Fraction(1, 4) + 1/6 + +For the QQ domain we do not want this behaviour because there should be no +remainder when dividing rational numbers. SymPy does not make use of this +aspect of mpq when gmpy2 is installed. Since this class is a fallback for that +case we do not bother implementing e.g. __mod__ so that we can be sure we +are not using it when gmpy2 is installed either. +""" + + +import operator +from math import gcd +from decimal import Decimal +from fractions import Fraction +import sys +from typing import Tuple as tTuple, Type + + +# Used for __hash__ +_PyHASH_MODULUS = sys.hash_info.modulus +_PyHASH_INF = sys.hash_info.inf + + +class PythonMPQ: + """Rational number implementation that is intended to be compatible with + gmpy2's mpq. + + Also slightly faster than fractions.Fraction. + + PythonMPQ should be treated as immutable although no effort is made to + prevent mutation (since that might slow down calculations). + """ + __slots__ = ('numerator', 'denominator') + + def __new__(cls, numerator, denominator=None): + """Construct PythonMPQ with gcd computation and checks""" + if denominator is not None: + # + # PythonMPQ(n, d): require n and d to be int and d != 0 + # + if isinstance(numerator, int) and isinstance(denominator, int): + # This is the slow part: + divisor = gcd(numerator, denominator) + numerator //= divisor + denominator //= divisor + return cls._new_check(numerator, denominator) + else: + # + # PythonMPQ(q) + # + # Here q can be PythonMPQ, int, Decimal, float, Fraction or str + # + if isinstance(numerator, int): + return cls._new(numerator, 1) + elif isinstance(numerator, PythonMPQ): + return cls._new(numerator.numerator, numerator.denominator) + + # Let Fraction handle Decimal/float conversion and str parsing + if isinstance(numerator, (Decimal, float, str)): + numerator = Fraction(numerator) + if isinstance(numerator, Fraction): + return cls._new(numerator.numerator, numerator.denominator) + # + # Reject everything else. This is more strict than mpq which allows + # things like mpq(Fraction, Fraction) or mpq(Decimal, any). The mpq + # behaviour is somewhat inconsistent so we choose to accept only a + # more strict subset of what mpq allows. + # + raise TypeError("PythonMPQ() requires numeric or string argument") + + @classmethod + def _new_check(cls, numerator, denominator): + """Construct PythonMPQ, check divide by zero and canonicalize signs""" + if not denominator: + raise ZeroDivisionError(f'Zero divisor {numerator}/{denominator}') + elif denominator < 0: + numerator = -numerator + denominator = -denominator + return cls._new(numerator, denominator) + + @classmethod + def _new(cls, numerator, denominator): + """Construct PythonMPQ efficiently (no checks)""" + obj = super().__new__(cls) + obj.numerator = numerator + obj.denominator = denominator + return obj + + def __int__(self): + """Convert to int (truncates towards zero)""" + p, q = self.numerator, self.denominator + if p < 0: + return -(-p//q) + return p//q + + def __float__(self): + """Convert to float (approximately)""" + return self.numerator / self.denominator + + def __bool__(self): + """True/False if nonzero/zero""" + return bool(self.numerator) + + def __eq__(self, other): + """Compare equal with PythonMPQ, int, float, Decimal or Fraction""" + if isinstance(other, PythonMPQ): + return (self.numerator == other.numerator + and self.denominator == other.denominator) + elif isinstance(other, self._compatible_types): + return self.__eq__(PythonMPQ(other)) + else: + return NotImplemented + + def __hash__(self): + """hash - same as mpq/Fraction""" + try: + dinv = pow(self.denominator, -1, _PyHASH_MODULUS) + except ValueError: + hash_ = _PyHASH_INF + else: + hash_ = hash(hash(abs(self.numerator)) * dinv) + result = hash_ if self.numerator >= 0 else -hash_ + return -2 if result == -1 else result + + def __reduce__(self): + """Deconstruct for pickling""" + return type(self), (self.numerator, self.denominator) + + def __str__(self): + """Convert to string""" + if self.denominator != 1: + return f"{self.numerator}/{self.denominator}" + else: + return f"{self.numerator}" + + def __repr__(self): + """Convert to string""" + return f"MPQ({self.numerator},{self.denominator})" + + def _cmp(self, other, op): + """Helper for lt/le/gt/ge""" + if not isinstance(other, self._compatible_types): + return NotImplemented + lhs = self.numerator * other.denominator + rhs = other.numerator * self.denominator + return op(lhs, rhs) + + def __lt__(self, other): + """self < other""" + return self._cmp(other, operator.lt) + + def __le__(self, other): + """self <= other""" + return self._cmp(other, operator.le) + + def __gt__(self, other): + """self > other""" + return self._cmp(other, operator.gt) + + def __ge__(self, other): + """self >= other""" + return self._cmp(other, operator.ge) + + def __abs__(self): + """abs(q)""" + return self._new(abs(self.numerator), self.denominator) + + def __pos__(self): + """+q""" + return self + + def __neg__(self): + """-q""" + return self._new(-self.numerator, self.denominator) + + def __add__(self, other): + """q1 + q2""" + if isinstance(other, PythonMPQ): + # + # This is much faster than the naive method used in the stdlib + # fractions module. Not sure where this method comes from + # though... + # + # Compare timings for something like: + # nums = range(1000) + # rats = [PythonMPQ(n, d) for n, d in zip(nums[:-5], nums[5:])] + # sum(rats) # <-- time this + # + ap, aq = self.numerator, self.denominator + bp, bq = other.numerator, other.denominator + g = gcd(aq, bq) + if g == 1: + p = ap*bq + aq*bp + q = bq*aq + else: + q1, q2 = aq//g, bq//g + p, q = ap*q2 + bp*q1, q1*q2 + g2 = gcd(p, g) + p, q = (p // g2), q * (g // g2) + + elif isinstance(other, int): + p = self.numerator + self.denominator * other + q = self.denominator + else: + return NotImplemented + + return self._new(p, q) + + def __radd__(self, other): + """z1 + q2""" + if isinstance(other, int): + p = self.numerator + self.denominator * other + q = self.denominator + return self._new(p, q) + else: + return NotImplemented + + def __sub__(self ,other): + """q1 - q2""" + if isinstance(other, PythonMPQ): + ap, aq = self.numerator, self.denominator + bp, bq = other.numerator, other.denominator + g = gcd(aq, bq) + if g == 1: + p = ap*bq - aq*bp + q = bq*aq + else: + q1, q2 = aq//g, bq//g + p, q = ap*q2 - bp*q1, q1*q2 + g2 = gcd(p, g) + p, q = (p // g2), q * (g // g2) + elif isinstance(other, int): + p = self.numerator - self.denominator*other + q = self.denominator + else: + return NotImplemented + + return self._new(p, q) + + def __rsub__(self, other): + """z1 - q2""" + if isinstance(other, int): + p = self.denominator * other - self.numerator + q = self.denominator + return self._new(p, q) + else: + return NotImplemented + + def __mul__(self, other): + """q1 * q2""" + if isinstance(other, PythonMPQ): + ap, aq = self.numerator, self.denominator + bp, bq = other.numerator, other.denominator + x1 = gcd(ap, bq) + x2 = gcd(bp, aq) + p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1)) + elif isinstance(other, int): + x = gcd(other, self.denominator) + p = self.numerator*(other//x) + q = self.denominator//x + else: + return NotImplemented + + return self._new(p, q) + + def __rmul__(self, other): + """z1 * q2""" + if isinstance(other, int): + x = gcd(self.denominator, other) + p = self.numerator*(other//x) + q = self.denominator//x + return self._new(p, q) + else: + return NotImplemented + + def __pow__(self, exp): + """q ** z""" + p, q = self.numerator, self.denominator + + if exp < 0: + p, q, exp = q, p, -exp + + return self._new_check(p**exp, q**exp) + + def __truediv__(self, other): + """q1 / q2""" + if isinstance(other, PythonMPQ): + ap, aq = self.numerator, self.denominator + bp, bq = other.numerator, other.denominator + x1 = gcd(ap, bp) + x2 = gcd(bq, aq) + p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1)) + elif isinstance(other, int): + x = gcd(other, self.numerator) + p = self.numerator//x + q = self.denominator*(other//x) + else: + return NotImplemented + + return self._new_check(p, q) + + def __rtruediv__(self, other): + """z / q""" + if isinstance(other, int): + x = gcd(self.numerator, other) + p = self.denominator*(other//x) + q = self.numerator//x + return self._new_check(p, q) + else: + return NotImplemented + + _compatible_types: tTuple[Type, ...] = () + +# +# These are the types that PythonMPQ will interoperate with for operations +# and comparisons such as ==, + etc. We define this down here so that we can +# include PythonMPQ in the list as well. +# +PythonMPQ._compatible_types = (PythonMPQ, int, Decimal, Fraction) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b5e4153bf84a6c3beb4e5e106dc0de956c33c37 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fa687d2b6be9dade259b7d68c97722c5740d13a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b64c9df16a2345992b364e0f69e9f8fd83c8793 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fee6dc5ad45722bd1055dbe6ad86e8545cea0759 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..720e72e104712dd9664aad15a8de8b753b9cd01a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9fe12ab5a275615fc844abaf93be01f4d519a61 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dfa24702327cb9fde223262c3cb33ebdacbc63a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..50ba10f9de911a8f9532af2c3e0cd1979cad1aa4 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py @@ -0,0 +1,313 @@ +import sympy +import tempfile +import os +from sympy.core.mod import Mod +from sympy.core.relational import Eq +from sympy.core.symbol import symbols +from sympy.external import import_module +from sympy.tensor import IndexedBase, Idx +from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError +from sympy.testing.pytest import skip + +numpy = import_module('numpy', min_module_version='1.6.1') +Cython = import_module('Cython', min_module_version='0.15.1') +f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']}) + +f2pyworks = False +if f2py: + try: + autowrap(symbols('x'), 'f95', 'f2py') + except (CodeWrapError, ImportError, OSError): + f2pyworks = False + else: + f2pyworks = True + +a, b, c = symbols('a b c') +n, m, d = symbols('n m d', integer=True) +A, B, C = symbols('A B C', cls=IndexedBase) +i = Idx('i', m) +j = Idx('j', n) +k = Idx('k', d) + + +def has_module(module): + """ + Return True if module exists, otherwise run skip(). + + module should be a string. + """ + # To give a string of the module name to skip(), this function takes a + # string. So we don't waste time running import_module() more than once, + # just map the three modules tested here in this dict. + modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py} + + if modnames[module]: + if module == 'f2py' and not f2pyworks: + skip("Couldn't run f2py.") + return True + skip("Couldn't import %s." % module) + +# +# test runners used by several language-backend combinations +# + +def runtest_autowrap_twice(language, backend): + f = autowrap((((a + b)/c)**5).expand(), language, backend) + g = autowrap((((a + b)/c)**4).expand(), language, backend) + + # check that autowrap updates the module name. Else, g gives the same as f + assert f(1, -2, 1) == -1.0 + assert g(1, -2, 1) == 1.0 + + +def runtest_autowrap_trace(language, backend): + has_module('numpy') + trace = autowrap(A[i, i], language, backend) + assert trace(numpy.eye(100)) == 100 + + +def runtest_autowrap_matrix_vector(language, backend): + has_module('numpy') + x, y = symbols('x y', cls=IndexedBase) + expr = Eq(y[i], A[i, j]*x[j]) + mv = autowrap(expr, language, backend) + + # compare with numpy's dot product + M = numpy.random.rand(10, 20) + x = numpy.random.rand(20) + y = numpy.dot(M, x) + assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13 + + +def runtest_autowrap_matrix_matrix(language, backend): + has_module('numpy') + expr = Eq(C[i, j], A[i, k]*B[k, j]) + matmat = autowrap(expr, language, backend) + + # compare with numpy's dot product + M1 = numpy.random.rand(10, 20) + M2 = numpy.random.rand(20, 15) + M3 = numpy.dot(M1, M2) + assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13 + + +def runtest_ufuncify(language, backend): + has_module('numpy') + a, b, c = symbols('a b c') + fabc = ufuncify([a, b, c], a*b + c, backend=backend) + facb = ufuncify([a, c, b], a*b + c, backend=backend) + grid = numpy.linspace(-2, 2, 50) + b = numpy.linspace(-5, 4, 50) + c = numpy.linspace(-1, 1, 50) + expected = grid*b + c + numpy.testing.assert_allclose(fabc(grid, b, c), expected) + numpy.testing.assert_allclose(facb(grid, c, b), expected) + + +def runtest_issue_10274(language, backend): + expr = (a - b + c)**(13) + tmp = tempfile.mkdtemp() + f = autowrap(expr, language, backend, tempdir=tmp, + helpers=('helper', a - b + c, (a, b, c))) + assert f(1, 1, 1) == 1 + + for file in os.listdir(tmp): + if not (file.startswith("wrapped_code_") and file.endswith(".c")): + continue + + with open(tmp + '/' + file) as fil: + lines = fil.readlines() + assert lines[0] == "/******************************************************************************\n" + assert "Code generated with SymPy " + sympy.__version__ in lines[1] + assert lines[2:] == [ + " * *\n", + " * See http://www.sympy.org/ for more information. *\n", + " * *\n", + " * This file is part of 'autowrap' *\n", + " ******************************************************************************/\n", + "#include " + '"' + file[:-1]+ 'h"' + "\n", + "#include \n", + "\n", + "double helper(double a, double b, double c) {\n", + "\n", + " double helper_result;\n", + " helper_result = a - b + c;\n", + " return helper_result;\n", + "\n", + "}\n", + "\n", + "double autofunc(double a, double b, double c) {\n", + "\n", + " double autofunc_result;\n", + " autofunc_result = pow(helper(a, b, c), 13);\n", + " return autofunc_result;\n", + "\n", + "}\n", + ] + + +def runtest_issue_15337(language, backend): + has_module('numpy') + # NOTE : autowrap was originally designed to only accept an iterable for + # the kwarg "helpers", but in issue 10274 the user mistakenly thought that + # if there was only a single helper it did not need to be passed via an + # iterable that wrapped the helper tuple. There were no tests for this + # behavior so when the code was changed to accept a single tuple it broke + # the original behavior. These tests below ensure that both now work. + a, b, c, d, e = symbols('a, b, c, d, e') + expr = (a - b + c - d + e)**13 + exp_res = (1. - 2. + 3. - 4. + 5.)**13 + + f = autowrap(expr, language, backend, args=(a, b, c, d, e), + helpers=('f1', a - b + c, (a, b, c))) + numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res) + + f = autowrap(expr, language, backend, args=(a, b, c, d, e), + helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d)))) + numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res) + + +def test_issue_15230(): + has_module('f2py') + + x, y = symbols('x, y') + expr = Mod(x, 3.0) - Mod(y, -2.0) + f = autowrap(expr, args=[x, y], language='F95') + exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf()) + assert abs(f(3.5, 2.7) - exp_res) < 1e-14 + + x, y = symbols('x, y', integer=True) + expr = Mod(x, 3) - Mod(y, -2) + f = autowrap(expr, args=[x, y], language='F95') + assert f(3, 2) == expr.xreplace({x: 3, y: 2}) + +# +# tests of language-backend combinations +# + +# f2py + + +def test_wrap_twice_f95_f2py(): + has_module('f2py') + runtest_autowrap_twice('f95', 'f2py') + + +def test_autowrap_trace_f95_f2py(): + has_module('f2py') + runtest_autowrap_trace('f95', 'f2py') + + +def test_autowrap_matrix_vector_f95_f2py(): + has_module('f2py') + runtest_autowrap_matrix_vector('f95', 'f2py') + + +def test_autowrap_matrix_matrix_f95_f2py(): + has_module('f2py') + runtest_autowrap_matrix_matrix('f95', 'f2py') + + +def test_ufuncify_f95_f2py(): + has_module('f2py') + runtest_ufuncify('f95', 'f2py') + + +def test_issue_15337_f95_f2py(): + has_module('f2py') + runtest_issue_15337('f95', 'f2py') + +# Cython + + +def test_wrap_twice_c_cython(): + has_module('Cython') + runtest_autowrap_twice('C', 'cython') + + +def test_autowrap_trace_C_Cython(): + has_module('Cython') + runtest_autowrap_trace('C99', 'cython') + + +def test_autowrap_matrix_vector_C_cython(): + has_module('Cython') + runtest_autowrap_matrix_vector('C99', 'cython') + + +def test_autowrap_matrix_matrix_C_cython(): + has_module('Cython') + runtest_autowrap_matrix_matrix('C99', 'cython') + + +def test_ufuncify_C_Cython(): + has_module('Cython') + runtest_ufuncify('C99', 'cython') + + +def test_issue_10274_C_cython(): + has_module('Cython') + runtest_issue_10274('C89', 'cython') + + +def test_issue_15337_C_cython(): + has_module('Cython') + runtest_issue_15337('C89', 'cython') + + +def test_autowrap_custom_printer(): + has_module('Cython') + + from sympy.core.numbers import pi + from sympy.utilities.codegen import C99CodeGen + from sympy.printing.c import C99CodePrinter + + class PiPrinter(C99CodePrinter): + def _print_Pi(self, expr): + return "S_PI" + + printer = PiPrinter() + gen = C99CodeGen(printer=printer) + gen.preprocessor_statements.append('#include "shortpi.h"') + + expr = pi * a + + expected = ( + '#include "%s"\n' + '#include \n' + '#include "shortpi.h"\n' + '\n' + 'double autofunc(double a) {\n' + '\n' + ' double autofunc_result;\n' + ' autofunc_result = S_PI*a;\n' + ' return autofunc_result;\n' + '\n' + '}\n' + ) + + tmpdir = tempfile.mkdtemp() + # write a trivial header file to use in the generated code + with open(os.path.join(tmpdir, 'shortpi.h'), 'w') as f: + f.write('#define S_PI 3.14') + + func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen) + + assert func(4.2) == 3.14 * 4.2 + + # check that the generated code is correct + for filename in os.listdir(tmpdir): + if filename.startswith('wrapped_code') and filename.endswith('.c'): + with open(os.path.join(tmpdir, filename)) as f: + lines = f.readlines() + expected = expected % filename.replace('.c', '.h') + assert ''.join(lines[7:]) == expected + + +# Numpy + +def test_ufuncify_numpy(): + # This test doesn't use Cython, but if Cython works, then there is a valid + # C compiler, which is needed. + has_module('Cython') + runtest_ufuncify('C99', 'numpy') diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..5449531a1217753c3c9d68cfec4d38852aeb0f8c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py @@ -0,0 +1,379 @@ +# This tests the compilation and execution of the source code generated with +# utilities.codegen. The compilation takes place in a temporary directory that +# is removed after the test. By default the test directory is always removed, +# but this behavior can be changed by setting the environment variable +# SYMPY_TEST_CLEAN_TEMP to: +# export SYMPY_TEST_CLEAN_TEMP=always : the default behavior. +# export SYMPY_TEST_CLEAN_TEMP=success : only remove the directories of working tests. +# export SYMPY_TEST_CLEAN_TEMP=never : never remove the directories with the test code. +# When a directory is not removed, the necessary information is printed on +# screen to find the files that belong to the (failed) tests. If a test does +# not fail, py.test captures all the output and you will not see the directories +# corresponding to the successful tests. Use the --nocapture option to see all +# the output. + +# All tests below have a counterpart in utilities/test/test_codegen.py. In the +# latter file, the resulting code is compared with predefined strings, without +# compilation or execution. + +# All the generated Fortran code should conform with the Fortran 95 standard, +# and all the generated C code should be ANSI C, which facilitates the +# incorporation in various projects. The tests below assume that the binary cc +# is somewhere in the path and that it can compile ANSI C code. + +from sympy.abc import x, y, z +from sympy.external import import_module +from sympy.testing.pytest import skip +from sympy.utilities.codegen import codegen, make_routine, get_code_generator +import sys +import os +import tempfile +import subprocess + + +pyodide_js = import_module('pyodide_js') + +# templates for the main program that will test the generated code. + +main_template = {} +main_template['F95'] = """ +program main + include "codegen.h" + integer :: result; + result = 0 + + %(statements)s + + call exit(result) +end program +""" + +main_template['C89'] = """ +#include "codegen.h" +#include +#include + +int main() { + int result = 0; + + %(statements)s + + return result; +} +""" +main_template['C99'] = main_template['C89'] +# templates for the numerical tests + +numerical_test_template = {} +numerical_test_template['C89'] = """ + if (fabs(%(call)s)>%(threshold)s) { + printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s); + result = -1; + } +""" +numerical_test_template['C99'] = numerical_test_template['C89'] + +numerical_test_template['F95'] = """ + if (abs(%(call)s)>%(threshold)s) then + write(6,"('Numerical validation failed:')") + write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s + result = -1; + end if +""" +# command sequences for supported compilers + +compile_commands = {} +compile_commands['cc'] = [ + "cc -c codegen.c -o codegen.o", + "cc -c main.c -o main.o", + "cc main.o codegen.o -lm -o test.exe" +] + +compile_commands['gfortran'] = [ + "gfortran -c codegen.f90 -o codegen.o", + "gfortran -ffree-line-length-none -c main.f90 -o main.o", + "gfortran main.o codegen.o -o test.exe" +] + +compile_commands['g95'] = [ + "g95 -c codegen.f90 -o codegen.o", + "g95 -ffree-line-length-huge -c main.f90 -o main.o", + "g95 main.o codegen.o -o test.exe" +] + +compile_commands['ifort'] = [ + "ifort -c codegen.f90 -o codegen.o", + "ifort -c main.f90 -o main.o", + "ifort main.o codegen.o -o test.exe" +] + +combinations_lang_compiler = [ + ('C89', 'cc'), + ('C99', 'cc'), + ('F95', 'ifort'), + ('F95', 'gfortran'), + ('F95', 'g95') +] + + +def try_run(commands): + """Run a series of commands and only return True if all ran fine.""" + if pyodide_js: + return False + with open(os.devnull, 'w') as null: + for command in commands: + retcode = subprocess.call(command, stdout=null, shell=True, + stderr=subprocess.STDOUT) + if retcode != 0: + return False + return True + + +def run_test(label, routines, numerical_tests, language, commands, friendly=True): + """A driver for the codegen tests. + + This driver assumes that a compiler ifort is present in the PATH and that + ifort is (at least) a Fortran 90 compiler. The generated code is written in + a temporary directory, together with a main program that validates the + generated code. The test passes when the compilation and the validation + run correctly. + """ + + # Check input arguments before touching the file system + language = language.upper() + assert language in main_template + assert language in numerical_test_template + + # Check that environment variable makes sense + clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower() + if clean not in ('always', 'success', 'never'): + raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.") + + # Do all the magic to compile, run and validate the test code + # 1) prepare the temporary working directory, switch to that dir + work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label) + oldwork = os.getcwd() + os.chdir(work) + + # 2) write the generated code + if friendly: + # interpret the routines as a name_expr list and call the friendly + # function codegen + codegen(routines, language, "codegen", to_files=True) + else: + code_gen = get_code_generator(language, "codegen") + code_gen.write(routines, "codegen", to_files=True) + + # 3) write a simple main program that links to the generated code, and that + # includes the numerical tests + test_strings = [] + for fn_name, args, expected, threshold in numerical_tests: + call_string = "%s(%s)-(%s)" % ( + fn_name, ",".join(str(arg) for arg in args), expected) + if language == "F95": + call_string = fortranize_double_constants(call_string) + threshold = fortranize_double_constants(str(threshold)) + test_strings.append(numerical_test_template[language] % { + "call": call_string, + "threshold": threshold, + }) + + if language == "F95": + f_name = "main.f90" + elif language.startswith("C"): + f_name = "main.c" + else: + raise NotImplementedError( + "FIXME: filename extension unknown for language: %s" % language) + + with open(f_name, "w") as f: + f.write( + main_template[language] % {'statements': "".join(test_strings)}) + + # 4) Compile and link + compiled = try_run(commands) + + # 5) Run if compiled + if compiled: + executed = try_run(["./test.exe"]) + else: + executed = False + + # 6) Clean up stuff + if clean == 'always' or (clean == 'success' and compiled and executed): + def safe_remove(filename): + if os.path.isfile(filename): + os.remove(filename) + safe_remove("codegen.f90") + safe_remove("codegen.c") + safe_remove("codegen.h") + safe_remove("codegen.o") + safe_remove("main.f90") + safe_remove("main.c") + safe_remove("main.o") + safe_remove("test.exe") + os.chdir(oldwork) + os.rmdir(work) + else: + print("TEST NOT REMOVED: %s" % work, file=sys.stderr) + os.chdir(oldwork) + + # 7) Do the assertions in the end + assert compiled, "failed to compile %s code with:\n%s" % ( + language, "\n".join(commands)) + assert executed, "failed to execute %s code from:\n%s" % ( + language, "\n".join(commands)) + + +def fortranize_double_constants(code_string): + """ + Replaces every literal float with literal doubles + """ + import re + pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+') + pattern_float = re.compile(r'\d+\.\d*(?!\d*d)') + + def subs_exp(matchobj): + return re.sub('[eE]', 'd', matchobj.group(0)) + + def subs_float(matchobj): + return "%sd0" % matchobj.group(0) + + code_string = pattern_exp.sub(subs_exp, code_string) + code_string = pattern_float.sub(subs_float, code_string) + + return code_string + + +def is_feasible(language, commands): + # This test should always work, otherwise the compiler is not present. + routine = make_routine("test", x) + numerical_tests = [ + ("test", ( 1.0,), 1.0, 1e-15), + ("test", (-1.0,), -1.0, 1e-15), + ] + try: + run_test("is_feasible", [routine], numerical_tests, language, commands, + friendly=False) + return True + except AssertionError: + return False + +valid_lang_commands = [] +invalid_lang_compilers = [] +for lang, compiler in combinations_lang_compiler: + commands = compile_commands[compiler] + if is_feasible(lang, commands): + valid_lang_commands.append((lang, commands)) + else: + invalid_lang_compilers.append((lang, compiler)) + +# We test all language-compiler combinations, just to report what is skipped + +def test_C89_cc(): + if ("C89", 'cc') in invalid_lang_compilers: + skip("`cc' command didn't work as expected (C89)") + + +def test_C99_cc(): + if ("C99", 'cc') in invalid_lang_compilers: + skip("`cc' command didn't work as expected (C99)") + + +def test_F95_ifort(): + if ("F95", 'ifort') in invalid_lang_compilers: + skip("`ifort' command didn't work as expected") + + +def test_F95_gfortran(): + if ("F95", 'gfortran') in invalid_lang_compilers: + skip("`gfortran' command didn't work as expected") + + +def test_F95_g95(): + if ("F95", 'g95') in invalid_lang_compilers: + skip("`g95' command didn't work as expected") + +# Here comes the actual tests + + +def test_basic_codegen(): + numerical_tests = [ + ("test", (1.0, 6.0, 3.0), 21.0, 1e-15), + ("test", (-1.0, 2.0, -2.5), -2.5, 1e-15), + ] + name_expr = [("test", (x + y)*z)] + for lang, commands in valid_lang_commands: + run_test("basic_codegen", name_expr, numerical_tests, lang, commands) + + +def test_intrinsic_math1_codegen(): + # not included: log10 + from sympy.core.evalf import N + from sympy.functions import ln + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) + from sympy.functions.elementary.integers import (ceiling, floor) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) + name_expr = [ + ("test_fabs", abs(x)), + ("test_acos", acos(x)), + ("test_asin", asin(x)), + ("test_atan", atan(x)), + ("test_cos", cos(x)), + ("test_cosh", cosh(x)), + ("test_log", log(x)), + ("test_ln", ln(x)), + ("test_sin", sin(x)), + ("test_sinh", sinh(x)), + ("test_sqrt", sqrt(x)), + ("test_tan", tan(x)), + ("test_tanh", tanh(x)), + ] + numerical_tests = [] + for name, expr in name_expr: + for xval in 0.2, 0.5, 0.8: + expected = N(expr.subs(x, xval)) + numerical_tests.append((name, (xval,), expected, 1e-14)) + for lang, commands in valid_lang_commands: + if lang.startswith("C"): + name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))] + else: + name_expr_C = [] + run_test("intrinsic_math1", name_expr + name_expr_C, + numerical_tests, lang, commands) + + +def test_instrinsic_math2_codegen(): + # not included: frexp, ldexp, modf, fmod + from sympy.core.evalf import N + from sympy.functions.elementary.trigonometric import atan2 + name_expr = [ + ("test_atan2", atan2(x, y)), + ("test_pow", x**y), + ] + numerical_tests = [] + for name, expr in name_expr: + for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8): + expected = N(expr.subs(x, xval).subs(y, yval)) + numerical_tests.append((name, (xval, yval), expected, 1e-14)) + for lang, commands in valid_lang_commands: + run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands) + + +def test_complicated_codegen(): + from sympy.core.evalf import N + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + name_expr = [ + ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), + ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), + ] + numerical_tests = [] + for name, expr in name_expr: + for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8): + expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval)) + numerical_tests.append((name, (xval, yval, zval), expected, 1e-12)) + for lang, commands in valid_lang_commands: + run_test( + "complicated_codegen", name_expr, numerical_tests, lang, commands) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py new file mode 100644 index 0000000000000000000000000000000000000000..0b954070c179282ed2bcf5735d802c5f22a3a261 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py @@ -0,0 +1,40 @@ +from sympy.external import import_module +from sympy.testing.pytest import warns + +# fixes issue that arose in addressing issue 6533 +def test_no_stdlib_collections(): + ''' + make sure we get the right collections when it is not part of a + larger list + ''' + import collections + matplotlib = import_module('matplotlib', + import_kwargs={'fromlist': ['cm', 'collections']}, + min_module_version='1.1.0', catch=(RuntimeError,)) + if matplotlib: + assert collections != matplotlib.collections + +def test_no_stdlib_collections2(): + ''' + make sure we get the right collections when it is not part of a + larger list + ''' + import collections + matplotlib = import_module('matplotlib', + import_kwargs={'fromlist': ['collections']}, + min_module_version='1.1.0', catch=(RuntimeError,)) + if matplotlib: + assert collections != matplotlib.collections + +def test_no_stdlib_collections3(): + '''make sure we get the right collections with no catch''' + import collections + matplotlib = import_module('matplotlib', + import_kwargs={'fromlist': ['cm', 'collections']}, + min_module_version='1.1.0') + if matplotlib: + assert collections != matplotlib.collections + +def test_min_module_version_python3_basestring_error(): + with warns(UserWarning): + import_module('mpmath', min_module_version='1000.0.1') diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd3f4bbadfe38f64080ea3088c8e1e7f92ab46c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py @@ -0,0 +1,333 @@ +# This testfile tests SymPy <-> NumPy compatibility + +# Don't test any SymPy features here. Just pure interaction with NumPy. +# Always write regular SymPy tests for anything, that can be tested in pure +# Python (without numpy). Here we test everything, that a user may need when +# using SymPy with NumPy +from sympy.external.importtools import version_tuple +from sympy.external import import_module + +numpy = import_module('numpy') +if numpy: + array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray +else: + #bin/test will not execute any tests now + disabled = True + + +from sympy.core.numbers import (Float, Integer, Rational) +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.trigonometric import sin +from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray) +from sympy.utilities.lambdify import lambdify +import sympy + +import mpmath +from sympy.abc import x, y, z +from sympy.utilities.decorator import conserve_mpmath_dps +from sympy.utilities.exceptions import ignore_warnings +from sympy.testing.pytest import raises + + +# first, systematically check, that all operations are implemented and don't +# raise an exception + + +def test_systematic_basic(): + def s(sympy_object, numpy_array): + _ = [sympy_object + numpy_array, + numpy_array + sympy_object, + sympy_object - numpy_array, + numpy_array - sympy_object, + sympy_object * numpy_array, + numpy_array * sympy_object, + sympy_object / numpy_array, + numpy_array / sympy_object, + sympy_object ** numpy_array, + numpy_array ** sympy_object] + x = Symbol("x") + y = Symbol("y") + sympy_objs = [ + Rational(2, 3), + Float("1.3"), + x, + y, + pow(x, y)*y, + Integer(5), + Float(5.5), + ] + numpy_objs = [ + array([1]), + array([3, 8, -1]), + array([x, x**2, Rational(5)]), + array([x/y*sin(y), 5, Rational(5)]), + ] + for x in sympy_objs: + for y in numpy_objs: + s(x, y) + + +# now some random tests, that test particular problems and that also +# check that the results of the operations are correct + +def test_basics(): + one = Rational(1) + zero = Rational(0) + assert array(1) == array(one) + assert array([one]) == array([one]) + assert array([x]) == array([x]) + assert array(x) == array(Symbol("x")) + assert array(one + x) == array(1 + x) + + X = array([one, zero, zero]) + assert (X == array([one, zero, zero])).all() + assert (X == array([one, 0, 0])).all() + + +def test_arrays(): + one = Rational(1) + zero = Rational(0) + X = array([one, zero, zero]) + Y = one*X + X = array([Symbol("a") + Rational(1, 2)]) + Y = X + X + assert Y == array([1 + 2*Symbol("a")]) + Y = Y + 1 + assert Y == array([2 + 2*Symbol("a")]) + Y = X - X + assert Y == array([0]) + + +def test_conversion1(): + a = list2numpy([x**2, x]) + #looks like an array? + assert isinstance(a, ndarray) + assert a[0] == x**2 + assert a[1] == x + assert len(a) == 2 + #yes, it's the array + + +def test_conversion2(): + a = 2*list2numpy([x**2, x]) + b = list2numpy([2*x**2, 2*x]) + assert (a == b).all() + + one = Rational(1) + zero = Rational(0) + X = list2numpy([one, zero, zero]) + Y = one*X + X = list2numpy([Symbol("a") + Rational(1, 2)]) + Y = X + X + assert Y == array([1 + 2*Symbol("a")]) + Y = Y + 1 + assert Y == array([2 + 2*Symbol("a")]) + Y = X - X + assert Y == array([0]) + + +def test_list2numpy(): + assert (array([x**2, x]) == list2numpy([x**2, x])).all() + + +def test_Matrix1(): + m = Matrix([[x, x**2], [5, 2/x]]) + assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all() + m = Matrix([[sin(x), x**2], [5, 2/x]]) + assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all() + + +def test_Matrix2(): + m = Matrix([[x, x**2], [5, 2/x]]) + with ignore_warnings(PendingDeprecationWarning): + assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all() + m = Matrix([[sin(x), x**2], [5, 2/x]]) + with ignore_warnings(PendingDeprecationWarning): + assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all() + + +def test_Matrix3(): + a = array([[2, 4], [5, 1]]) + assert Matrix(a) == Matrix([[2, 4], [5, 1]]) + assert Matrix(a) != Matrix([[2, 4], [5, 2]]) + a = array([[sin(2), 4], [5, 1]]) + assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) + assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]]) + + +def test_Matrix4(): + with ignore_warnings(PendingDeprecationWarning): + a = matrix([[2, 4], [5, 1]]) + assert Matrix(a) == Matrix([[2, 4], [5, 1]]) + assert Matrix(a) != Matrix([[2, 4], [5, 2]]) + with ignore_warnings(PendingDeprecationWarning): + a = matrix([[sin(2), 4], [5, 1]]) + assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) + assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]]) + + +def test_Matrix_sum(): + M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) + with ignore_warnings(PendingDeprecationWarning): + m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]]) + assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) + assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) + assert M + m == M.add(m) + + +def test_Matrix_mul(): + M = Matrix([[1, 2, 3], [x, y, x]]) + with ignore_warnings(PendingDeprecationWarning): + m = matrix([[2, 4], [x, 6], [x, z**2]]) + assert M*m == Matrix([ + [ 2 + 5*x, 16 + 3*z**2], + [2*x + x*y + x**2, 4*x + 6*y + x*z**2], + ]) + + assert m*M == Matrix([ + [ 2 + 4*x, 4 + 4*y, 6 + 4*x], + [ 7*x, 2*x + 6*y, 9*x], + [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2], + ]) + a = array([2]) + assert a[0] * M == 2 * M + assert M * a[0] == 2 * M + + +def test_Matrix_array(): + class matarray: + def __array__(self): + from numpy import array + return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + matarr = matarray() + assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + + +def test_matrix2numpy(): + a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]])) + assert isinstance(a, ndarray) + assert a.shape == (2, 2) + assert a[0, 0] == 1 + assert a[0, 1] == x**2 + assert a[1, 0] == 3*sin(x) + assert a[1, 1] == 0 + + +def test_matrix2numpy_conversion(): + a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) + b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) + assert (matrix2numpy(a) == b).all() + assert matrix2numpy(a).dtype == numpy.dtype('object') + + c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8') + d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64') + assert c.dtype == numpy.dtype('int8') + assert d.dtype == numpy.dtype('float64') + + +def test_issue_3728(): + assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all() + assert (Rational(1, 2) + array( + [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all() + assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all() + assert (Float("0.5") + array( + [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all() + + +@conserve_mpmath_dps +def test_lambdify(): + mpmath.mp.dps = 16 + sin02 = mpmath.mpf("0.198669330795061215459412627") + f = lambdify(x, sin(x), "numpy") + prec = 1e-15 + assert -prec < f(0.2) - sin02 < prec + + # if this succeeds, it can't be a numpy function + + if version_tuple(numpy.__version__) >= version_tuple('1.17'): + with raises(TypeError): + f(x) + else: + with raises(AttributeError): + f(x) + + +def test_lambdify_matrix(): + f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"]) + assert (f(1) == array([[1, 2], [1, 2]])).all() + + +def test_lambdify_matrix_multi_input(): + M = sympy.Matrix([[x**2, x*y, x*z], + [y*x, y**2, y*z], + [z*x, z*y, z**2]]) + f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"]) + + xh, yh, zh = 1.0, 2.0, 3.0 + expected = array([[xh**2, xh*yh, xh*zh], + [yh*xh, yh**2, yh*zh], + [zh*xh, zh*yh, zh**2]]) + actual = f(xh, yh, zh) + assert numpy.allclose(actual, expected) + + +def test_lambdify_matrix_vec_input(): + X = sympy.DeferredVector('X') + M = Matrix([ + [X[0]**2, X[0]*X[1], X[0]*X[2]], + [X[1]*X[0], X[1]**2, X[1]*X[2]], + [X[2]*X[0], X[2]*X[1], X[2]**2]]) + f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"]) + + Xh = array([1.0, 2.0, 3.0]) + expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]], + [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]], + [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]]) + actual = f(Xh) + assert numpy.allclose(actual, expected) + + +def test_lambdify_transl(): + from sympy.utilities.lambdify import NUMPY_TRANSLATIONS + for sym, mat in NUMPY_TRANSLATIONS.items(): + assert sym in sympy.__dict__ + assert mat in numpy.__dict__ + + +def test_symarray(): + """Test creation of numpy arrays of SymPy symbols.""" + + import numpy as np + import numpy.testing as npt + + syms = symbols('_0,_1,_2') + s1 = symarray("", 3) + s2 = symarray("", 3) + npt.assert_array_equal(s1, np.array(syms, dtype=object)) + assert s1[0] == s2[0] + + a = symarray('a', 3) + b = symarray('b', 3) + assert not(a[0] == b[0]) + + asyms = symbols('a_0,a_1,a_2') + npt.assert_array_equal(a, np.array(asyms, dtype=object)) + + # Multidimensional checks + a2d = symarray('a', (2, 3)) + assert a2d.shape == (2, 3) + a00, a12 = symbols('a_0_0,a_1_2') + assert a2d[0, 0] == a00 + assert a2d[1, 2] == a12 + + a3d = symarray('a', (2, 3, 2)) + assert a3d.shape == (2, 3, 2) + a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1') + assert a3d[0, 0, 0] == a000 + assert a3d[1, 2, 0] == a120 + assert a3d[1, 2, 1] == a121 + + +def test_vectorize(): + assert (numpy.vectorize( + sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all() diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py new file mode 100644 index 0000000000000000000000000000000000000000..137cfdf5c858544f0811ae666f000cfb368787a0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py @@ -0,0 +1,176 @@ +""" +test_pythonmpq.py + +Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is +installed run the same tests for both. +""" +from fractions import Fraction +from decimal import Decimal +import pickle +from typing import Callable, List, Tuple, Type + +from sympy.testing.pytest import raises + +from sympy.external.pythonmpq import PythonMPQ + +# +# If gmpy2 is installed then run the tests for both mpq and PythonMPQ. +# That should ensure consistency between the implementation here and mpq. +# +rational_types: List[Tuple[Callable, Type, Callable, Type]] +rational_types = [(PythonMPQ, PythonMPQ, int, int)] +try: + from gmpy2 import mpq, mpz + rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1)))) +except ImportError: + pass + + +def test_PythonMPQ(): + # + # Test PythonMPQ and also mpq if gmpy/gmpy2 is installed. + # + for Q, TQ, Z, TZ in rational_types: + + def check_Q(q): + assert isinstance(q, TQ) + assert isinstance(q.numerator, TZ) + assert isinstance(q.denominator, TZ) + return q.numerator, q.denominator + + # Check construction from different types + assert check_Q(Q(3)) == (3, 1) + assert check_Q(Q(3, 5)) == (3, 5) + assert check_Q(Q(Q(3, 5))) == (3, 5) + assert check_Q(Q(0.5)) == (1, 2) + assert check_Q(Q('0.5')) == (1, 2) + assert check_Q(Q(Fraction(3, 5))) == (3, 5) + + # https://github.com/aleaxit/gmpy/issues/327 + if Q is PythonMPQ: + assert check_Q(Q(Decimal('0.6'))) == (3, 5) + + # Invalid types + raises(TypeError, lambda: Q([])) + raises(TypeError, lambda: Q([], [])) + + # Check normalisation of signs + assert check_Q(Q(2, 3)) == (2, 3) + assert check_Q(Q(-2, 3)) == (-2, 3) + assert check_Q(Q(2, -3)) == (-2, 3) + assert check_Q(Q(-2, -3)) == (2, 3) + + # Check gcd calculation + assert check_Q(Q(12, 8)) == (3, 2) + + # __int__/__float__ + assert int(Q(5, 3)) == 1 + assert int(Q(-5, 3)) == -1 + assert float(Q(5, 2)) == 2.5 + assert float(Q(-5, 2)) == -2.5 + + # __str__/__repr__ + assert str(Q(2, 1)) == "2" + assert str(Q(1, 2)) == "1/2" + if Q is PythonMPQ: + assert repr(Q(2, 1)) == "MPQ(2,1)" + assert repr(Q(1, 2)) == "MPQ(1,2)" + else: + assert repr(Q(2, 1)) == "mpq(2,1)" + assert repr(Q(1, 2)) == "mpq(1,2)" + + # __bool__ + assert bool(Q(1, 2)) is True + assert bool(Q(0)) is False + + # __eq__/__ne__ + assert (Q(2, 3) == Q(2, 3)) is True + assert (Q(2, 3) == Q(2, 5)) is False + assert (Q(2, 3) != Q(2, 3)) is False + assert (Q(2, 3) != Q(2, 5)) is True + + # __hash__ + assert hash(Q(3, 5)) == hash(Fraction(3, 5)) + + # __reduce__ + q = Q(2, 3) + assert pickle.loads(pickle.dumps(q)) == q + + # __ge__/__gt__/__le__/__lt__ + assert (Q(1, 3) < Q(2, 3)) is True + assert (Q(2, 3) < Q(2, 3)) is False + assert (Q(2, 3) < Q(1, 3)) is False + assert (Q(-2, 3) < Q(1, 3)) is True + assert (Q(1, 3) < Q(-2, 3)) is False + + assert (Q(1, 3) <= Q(2, 3)) is True + assert (Q(2, 3) <= Q(2, 3)) is True + assert (Q(2, 3) <= Q(1, 3)) is False + assert (Q(-2, 3) <= Q(1, 3)) is True + assert (Q(1, 3) <= Q(-2, 3)) is False + + assert (Q(1, 3) > Q(2, 3)) is False + assert (Q(2, 3) > Q(2, 3)) is False + assert (Q(2, 3) > Q(1, 3)) is True + assert (Q(-2, 3) > Q(1, 3)) is False + assert (Q(1, 3) > Q(-2, 3)) is True + + assert (Q(1, 3) >= Q(2, 3)) is False + assert (Q(2, 3) >= Q(2, 3)) is True + assert (Q(2, 3) >= Q(1, 3)) is True + assert (Q(-2, 3) >= Q(1, 3)) is False + assert (Q(1, 3) >= Q(-2, 3)) is True + + # __abs__/__pos__/__neg__ + assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3) + assert +Q(2, 3) == Q(2, 3) + assert -Q(2, 3) == Q(-2, 3) + + # __add__/__radd__ + assert Q(2, 3) + Q(5, 7) == Q(29, 21) + assert Q(2, 3) + 1 == Q(5, 3) + assert 1 + Q(2, 3) == Q(5, 3) + raises(TypeError, lambda: [] + Q(1)) + raises(TypeError, lambda: Q(1) + []) + + # __sub__/__rsub__ + assert Q(2, 3) - Q(5, 7) == Q(-1, 21) + assert Q(2, 3) - 1 == Q(-1, 3) + assert 1 - Q(2, 3) == Q(1, 3) + raises(TypeError, lambda: [] - Q(1)) + raises(TypeError, lambda: Q(1) - []) + + # __mul__/__rmul__ + assert Q(2, 3) * Q(5, 7) == Q(10, 21) + assert Q(2, 3) * 1 == Q(2, 3) + assert 1 * Q(2, 3) == Q(2, 3) + raises(TypeError, lambda: [] * Q(1)) + raises(TypeError, lambda: Q(1) * []) + + # __pow__/__rpow__ + assert Q(2, 3) ** 2 == Q(4, 9) + assert Q(2, 3) ** 1 == Q(2, 3) + assert Q(-2, 3) ** 2 == Q(4, 9) + assert Q(-2, 3) ** -1 == Q(-3, 2) + if Q is PythonMPQ: + raises(TypeError, lambda: 1 ** Q(2, 3)) + raises(TypeError, lambda: Q(1, 4) ** Q(1, 2)) + raises(TypeError, lambda: [] ** Q(1)) + raises(TypeError, lambda: Q(1) ** []) + + # __div__/__rdiv__ + assert Q(2, 3) / Q(5, 7) == Q(14, 15) + assert Q(2, 3) / 1 == Q(2, 3) + assert 1 / Q(2, 3) == Q(3, 2) + raises(TypeError, lambda: [] / Q(1)) + raises(TypeError, lambda: Q(1) / []) + raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0)) + + # __divmod__ + if Q is PythonMPQ: + raises(TypeError, lambda: Q(2, 3) // Q(1, 3)) + raises(TypeError, lambda: Q(2, 3) % Q(1, 3)) + raises(TypeError, lambda: 1 // Q(1, 3)) + raises(TypeError, lambda: 1 % Q(1, 3)) + raises(TypeError, lambda: Q(2, 3) // 1) + raises(TypeError, lambda: Q(2, 3) % 1) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py new file mode 100644 index 0000000000000000000000000000000000000000..3746d1a311eb68bb1af16e18ab152c7236b42bb5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py @@ -0,0 +1,35 @@ +# This testfile tests SymPy <-> SciPy compatibility + +# Don't test any SymPy features here. Just pure interaction with SciPy. +# Always write regular SymPy tests for anything, that can be tested in pure +# Python (without scipy). Here we test everything, that a user may need when +# using SymPy with SciPy + +from sympy.external import import_module + +scipy = import_module('scipy') +if not scipy: + #bin/test will not execute any tests now + disabled = True + +from sympy.functions.special.bessel import jn_zeros + + +def eq(a, b, tol=1e-6): + for x, y in zip(a, b): + if not (abs(x - y) < tol): + return False + return True + + +def test_jn_zeros(): + assert eq(jn_zeros(0, 4, method="scipy"), + [3.141592, 6.283185, 9.424777, 12.566370]) + assert eq(jn_zeros(1, 4, method="scipy"), + [4.493409, 7.725251, 10.904121, 14.066193]) + assert eq(jn_zeros(2, 4, method="scipy"), + [5.763459, 9.095011, 12.322940, 15.514603]) + assert eq(jn_zeros(3, 4, method="scipy"), + [6.987932, 10.417118, 13.698023, 16.923621]) + assert eq(jn_zeros(4, 4, method="scipy"), + [8.182561, 11.704907, 15.039664, 18.301255]) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e050a5196fc4d524a6fa2288eea7f02f0b9a922 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__init__.py @@ -0,0 +1,67 @@ +""" +Number theory module (primes, etc) +""" + +from .generate import nextprime, prevprime, prime, primepi, primerange, \ + randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi +from .primetest import isprime, is_gaussian_prime +from .factor_ import divisors, proper_divisors, factorint, multiplicity, \ + multiplicity_in_factorial, perfect_power, pollard_pm1, pollard_rho, \ + primefactors, totient, trailing, \ + divisor_count, proper_divisor_count, divisor_sigma, factorrat, \ + reduced_totient, primenu, primeomega, mersenne_prime_exponent, \ + is_perfect, is_mersenne_prime, is_abundant, is_deficient, is_amicable, \ + abundance, dra, drm + +from .partitions_ import npartitions +from .residue_ntheory import is_primitive_root, is_quad_residue, \ + legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \ + primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \ + discrete_log, quadratic_congruence, polynomial_congruence +from .multinomial import binomial_coefficients, binomial_coefficients_list, \ + multinomial_coefficients +from .continued_fraction import continued_fraction_periodic, \ + continued_fraction_iterator, continued_fraction_reduce, \ + continued_fraction_convergents, continued_fraction +from .digits import count_digits, digits, is_palindromic +from .egyptian_fraction import egyptian_fraction +from .ecm import ecm +from .qs import qs +__all__ = [ + 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + + 'isprime', 'is_gaussian_prime', + + + 'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power', + 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', 'trailing', + 'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat', + 'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent', + 'is_perfect', 'is_mersenne_prime', 'is_abundant', 'is_deficient', 'is_amicable', + 'abundance', 'dra', 'drm', 'multiplicity_in_factorial', + + 'npartitions', + + 'is_primitive_root', 'is_quad_residue', 'legendre_symbol', + 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'mobius', 'discrete_log', 'quadratic_congruence', 'polynomial_congruence', + + 'binomial_coefficients', 'binomial_coefficients_list', + 'multinomial_coefficients', + + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', + + 'digits', + 'count_digits', + 'is_palindromic', + + 'egyptian_fraction', + + 'ecm', + + 'qs', +] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py new file mode 100644 index 0000000000000000000000000000000000000000..03a571b59d9b1608aa22cb8e7aff3010cda35633 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py @@ -0,0 +1,159 @@ +''' +This implementation is a heavily modified fixed point implementation of +BBP_formula for calculating the nth position of pi. The original hosted +at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python) + +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sub-license, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Modifications: + +1.Once the nth digit and desired number of digits is selected, the +number of digits of working precision is calculated to ensure that +the hexadecimal digits returned are accurate. This is calculated as + + int(math.log(start + prec)/math.log(16) + prec + 3) + --------------------------------------- -------- + / / + number of hex digits additional digits + +This was checked by the following code which completed without +errors (and dig are the digits included in the test_bbp.py file): + + for i in range(0,1000): + for j in range(1,1000): + a, b = pi_hex_digits(i, j), dig[i:i+j] + if a != b: + print('%s\n%s'%(a,b)) + +Deceasing the additional digits by 1 generated errors, so '3' is +the smallest additional precision needed to calculate the above +loop without errors. The following trailing 10 digits were also +checked to be accurate (and the times were slightly faster with +some of the constant modifications that were made): + + >> from time import time + >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t + ('e90c6cc0ac', 0.0) + >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t + ('26aab49ec6', 0.17100000381469727) + >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t + ('a22673c1a5', 4.7109999656677246) + >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t + ('9ffd342362', 59.985999822616577) + >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t + ('c1a42e06a1', 689.51800012588501) + +2. The while loop to evaluate whether the series has converged quits +when the addition amount `dt` has dropped to zero. + +3. the formatting string to convert the decimal to hexadecimal is +calculated for the given precision. + +4. pi_hex_digits(n) changed to have coefficient to the formula in an +array (perhaps just a matter of preference). + +''' + +import math +from sympy.utilities.misc import as_int + + +def _series(j, n, prec=14): + + # Left sum from the bbp algorithm + s = 0 + D = _dn(n, prec) + D4 = 4 * D + k = 0 + d = 8 * k + j + for k in range(n + 1): + s += (pow(16, n - k, d) << D4) // d + d += 8 + + # Right sum iterates to infinity for full precision, but we + # stop at the point where one iteration is beyond the precision + # specified. + + t = 0 + k = n + 1 + e = 4*(D + n - k) + d = 8 * k + j + while True: + dt = (1 << e) // d + if not dt: + break + t += dt + # k += 1 + e -= 4 + d += 8 + total = s + t + + return total + + +def pi_hex_digits(n, prec=14): + """Returns a string containing ``prec`` (default 14) digits + starting at the nth digit of pi in hex. Counting of digits + starts at 0 and the decimal is not counted, so for n = 0 the + returned value starts with 3; n = 1 corresponds to the first + digit past the decimal point (which in hex is 2). + + Examples + ======== + + >>> from sympy.ntheory.bbp_pi import pi_hex_digits + >>> pi_hex_digits(0) + '3243f6a8885a30' + >>> pi_hex_digits(0, 3) + '324' + + References + ========== + + .. [1] http://www.numberworld.org/digits/Pi/ + """ + n, prec = as_int(n), as_int(prec) + if n < 0: + raise ValueError('n cannot be negative') + if prec == 0: + return '' + + # main of implementation arrays holding formulae coefficients + n -= 1 + a = [4, 2, 1, 1] + j = [1, 4, 5, 6] + + #formulae + D = _dn(n, prec) + x = + (a[0]*_series(j[0], n, prec) + - a[1]*_series(j[1], n, prec) + - a[2]*_series(j[2], n, prec) + - a[3]*_series(j[3], n, prec)) & (16**D - 1) + + s = ("%0" + "%ix" % prec) % (x // 16**(D - prec)) + return s + + +def _dn(n, prec): + # controller for n dependence on precision + # n = starting digit index + # prec = the number of total digits to compute + n += 1 # because we subtract 1 for _series + return int(math.log(n + prec)/math.log(16) + prec + 3) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..579ac3d4cd369829d7ac6c42ce86d4ba7f894646 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py @@ -0,0 +1,351 @@ +from __future__ import annotations +from sympy.core.exprtools import factor_terms +from sympy.core.numbers import Integer, Rational +from sympy.core.singleton import S +from sympy.core.symbol import Dummy +from sympy.core.sympify import _sympify +from sympy.utilities.misc import as_int + + +def continued_fraction(a) -> list: + """Return the continued fraction representation of a Rational or + quadratic irrational. + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction + >>> from sympy import sqrt + >>> continued_fraction((1 + 2*sqrt(3))/5) + [0, 1, [8, 3, 34, 3]] + + See Also + ======== + continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents + """ + e = _sympify(a) + if all(i.is_Rational for i in e.atoms()): + if e.is_Integer: + return continued_fraction_periodic(e, 1, 0) + elif e.is_Rational: + return continued_fraction_periodic(e.p, e.q, 0) + elif e.is_Pow and e.exp is S.Half and e.base.is_Integer: + return continued_fraction_periodic(0, 1, e.base) + elif e.is_Mul and len(e.args) == 2 and ( + e.args[0].is_Rational and + e.args[1].is_Pow and + e.args[1].base.is_Integer and + e.args[1].exp is S.Half): + a, b = e.args + return continued_fraction_periodic(0, a.q, b.base, a.p) + else: + # this should not have to work very hard- no + # simplification, cancel, etc... which should be + # done by the user. e.g. This is a fancy 1 but + # the user should simplify it first: + # sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2) + p, d = e.expand().as_numer_denom() + if d.is_Integer: + if p.is_Rational: + return continued_fraction_periodic(p, d) + # look for a + b*c + # with c = sqrt(s) + if p.is_Add and len(p.args) == 2: + a, bc = p.args + else: + a = S.Zero + bc = p + if a.is_Integer: + b = S.NaN + if bc.is_Mul and len(bc.args) == 2: + b, c = bc.args + elif bc.is_Pow: + b = Integer(1) + c = bc + if b.is_Integer and ( + c.is_Pow and c.exp is S.Half and + c.base.is_Integer): + # (a + b*sqrt(c))/d + c = c.base + return continued_fraction_periodic(a, d, c, b) + raise ValueError( + 'expecting a rational or quadratic irrational, not %s' % e) + + +def continued_fraction_periodic(p, q, d=0, s=1) -> list: + r""" + Find the periodic continued fraction expansion of a quadratic irrational. + + Compute the continued fraction expansion of a rational or a + quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where + `p`, `q \ne 0` and `d \ge 0` are integers. + + Returns the continued fraction representation (canonical form) as + a list of integers, optionally ending (for quadratic irrationals) + with list of integers representing the repeating digits. + + Parameters + ========== + + p : int + the rational part of the number's numerator + q : int + the denominator of the number + d : int, optional + the irrational part (discriminator) of the number's numerator + s : int, optional + the coefficient of the irrational part + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic + >>> continued_fraction_periodic(3, 2, 7) + [2, [1, 4, 1, 1]] + + Golden ratio has the simplest continued fraction expansion: + + >>> continued_fraction_periodic(1, 2, 5) + [[1]] + + If the discriminator is zero or a perfect square then the number will be a + rational number: + + >>> continued_fraction_periodic(4, 3, 0) + [1, 3] + >>> continued_fraction_periodic(4, 3, 49) + [3, 1, 2] + + See Also + ======== + + continued_fraction_iterator, continued_fraction_reduce + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction + .. [2] K. Rosen. Elementary Number theory and its applications. + Addison-Wesley, 3 Sub edition, pages 379-381, January 1992. + + """ + from sympy.functions import sqrt, floor + + p, q, d, s = list(map(as_int, [p, q, d, s])) + + if d < 0: + raise ValueError("expected non-negative for `d` but got %s" % d) + + if q == 0: + raise ValueError("The denominator cannot be 0.") + + if not s: + d = 0 + + # check for rational case + sd = sqrt(d) + if sd.is_Integer: + return list(continued_fraction_iterator(Rational(p + s*sd, q))) + + # irrational case with sd != Integer + if q < 0: + p, q, s = -p, -q, -s + + n = (p + s*sd)/q + if n < 0: + w = floor(-n) + f = -n - w + one_f = continued_fraction(1 - f) # 1-f < 1 so cf is [0 ... [...]] + one_f[0] -= w + 1 + return one_f + + d *= s**2 + sd *= s + + if (d - p**2)%q: + d *= q**2 + sd *= q + p *= q + q *= q + + terms: list[int] = [] + pq = {} + + while (p, q) not in pq: + pq[(p, q)] = len(terms) + terms.append((p + sd)//q) + p = terms[-1]*q - p + q = (d - p**2)//q + + i = pq[(p, q)] + return terms[:i] + [terms[i:]] # type: ignore + + +def continued_fraction_reduce(cf): + """ + Reduce a continued fraction to a rational or quadratic irrational. + + Compute the rational or quadratic irrational number from its + terminating or periodic continued fraction expansion. The + continued fraction expansion (cf) should be supplied as a + terminating iterator supplying the terms of the expansion. For + terminating continued fractions, this is equivalent to + ``list(continued_fraction_convergents(cf))[-1]``, only a little more + efficient. If the expansion has a repeating part, a list of the + repeating terms should be returned as the last element from the + iterator. This is the format returned by + continued_fraction_periodic. + + For quadratic irrationals, returns the largest solution found, + which is generally the one sought, if the fraction is in canonical + form (all terms positive except possibly the first). + + Examples + ======== + + >>> from sympy.ntheory.continued_fraction import continued_fraction_reduce + >>> continued_fraction_reduce([1, 2, 3, 4, 5]) + 225/157 + >>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2]) + -256/233 + >>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10) + 2.718281835 + >>> continued_fraction_reduce([1, 4, 2, [3, 1]]) + (sqrt(21) + 287)/238 + >>> continued_fraction_reduce([[1]]) + (1 + sqrt(5))/2 + >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic + >>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13)) + (sqrt(13) + 8)/5 + + See Also + ======== + + continued_fraction_periodic + + """ + from sympy.solvers import solve + + period = [] + x = Dummy('x') + + def untillist(cf): + for nxt in cf: + if isinstance(nxt, list): + period.extend(nxt) + yield x + break + yield nxt + + a = S.Zero + for a in continued_fraction_convergents(untillist(cf)): + pass + + if period: + y = Dummy('y') + solns = solve(continued_fraction_reduce(period + [y]) - y, y) + solns.sort() + pure = solns[-1] + rv = a.subs(x, pure).radsimp() + else: + rv = a + if rv.is_Add: + rv = factor_terms(rv) + if rv.is_Mul and rv.args[0] == -1: + rv = rv.func(*rv.args) + return rv + + +def continued_fraction_iterator(x): + """ + Return continued fraction expansion of x as iterator. + + Examples + ======== + + >>> from sympy import Rational, pi + >>> from sympy.ntheory.continued_fraction import continued_fraction_iterator + + >>> list(continued_fraction_iterator(Rational(3, 8))) + [0, 2, 1, 2] + >>> list(continued_fraction_iterator(Rational(-3, 8))) + [-1, 1, 1, 1, 2] + + >>> for i, v in enumerate(continued_fraction_iterator(pi)): + ... if i > 7: + ... break + ... print(v) + 3 + 7 + 15 + 1 + 292 + 1 + 1 + 1 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Continued_fraction + + """ + from sympy.functions import floor + while True: + i = floor(x) + yield i + x -= i + if not x: + break + x = 1/x + + +def continued_fraction_convergents(cf): + """ + Return an iterator over the convergents of a continued fraction (cf). + + The parameter should be an iterable returning successive + partial quotients of the continued fraction, such as might be + returned by continued_fraction_iterator. In computing the + convergents, the continued fraction need not be strictly in + canonical form (all integers, all but the first positive). + Rational and negative elements may be present in the expansion. + + Examples + ======== + + >>> from sympy.core import pi + >>> from sympy import S + >>> from sympy.ntheory.continued_fraction import \ + continued_fraction_convergents, continued_fraction_iterator + + >>> list(continued_fraction_convergents([0, 2, 1, 2])) + [0, 1/2, 1/3, 3/8] + + >>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')])) + [1, 3, 19/5, 7] + + >>> it = continued_fraction_convergents(continued_fraction_iterator(pi)) + >>> for n in range(7): + ... print(next(it)) + 3 + 22/7 + 333/106 + 355/113 + 103993/33102 + 104348/33215 + 208341/66317 + + See Also + ======== + + continued_fraction_iterator + + """ + p_2, q_2 = S.Zero, S.One + p_1, q_1 = S.One, S.Zero + for a in cf: + p, q = a*p_1 + p_2, a*q_1 + q_2 + p_2, q_2 = p_1, q_1 + p_1, q_1 = p, q + yield p/q diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/digits.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/digits.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d903ea77200737e00dbb4bc2c09b7fa2291863 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/digits.py @@ -0,0 +1,143 @@ +from collections import defaultdict + +from sympy.utilities.iterables import multiset, is_palindromic as _palindromic +from sympy.utilities.misc import as_int + + +def digits(n, b=10, digits=None): + """ + Return a list of the digits of ``n`` in base ``b``. The first + element in the list is ``b`` (or ``-b`` if ``n`` is negative). + + Examples + ======== + + >>> from sympy.ntheory.digits import digits + >>> digits(35) + [10, 3, 5] + + If the number is negative, the negative sign will be placed on the + base (which is the first element in the returned list): + + >>> digits(-35) + [-10, 3, 5] + + Bases other than 10 (and greater than 1) can be selected with ``b``: + + >>> digits(27, b=2) + [2, 1, 1, 0, 1, 1] + + Use the ``digits`` keyword if a certain number of digits is desired: + + >>> digits(35, digits=4) + [10, 0, 0, 3, 5] + + Parameters + ========== + + n: integer + The number whose digits are returned. + + b: integer + The base in which digits are computed. + + digits: integer (or None for all digits) + The number of digits to be returned (padded with zeros, if + necessary). + + """ + + b = as_int(b) + n = as_int(n) + if b < 2: + raise ValueError("b must be greater than 1") + else: + x, y = abs(n), [] + while x >= b: + x, r = divmod(x, b) + y.append(r) + y.append(x) + y.append(-b if n < 0 else b) + y.reverse() + ndig = len(y) - 1 + if digits is not None: + if ndig > digits: + raise ValueError( + "For %s, at least %s digits are needed." % (n, ndig)) + elif ndig < digits: + y[1:1] = [0]*(digits - ndig) + return y + + +def count_digits(n, b=10): + """ + Return a dictionary whose keys are the digits of ``n`` in the + given base, ``b``, with keys indicating the digits appearing in the + number and values indicating how many times that digit appeared. + + Examples + ======== + + >>> from sympy.ntheory import count_digits + + >>> count_digits(1111339) + {1: 4, 3: 2, 9: 1} + + The digits returned are always represented in base-10 + but the number itself can be entered in any format that is + understood by Python; the base of the number can also be + given if it is different than 10: + + >>> n = 0xFA; n + 250 + >>> count_digits(_) + {0: 1, 2: 1, 5: 1} + >>> count_digits(n, 16) + {10: 1, 15: 1} + + The default dictionary will return a 0 for any digit that did + not appear in the number. For example, which digits appear 7 + times in ``77!``: + + >>> from sympy import factorial + >>> c77 = count_digits(factorial(77)) + >>> [i for i in range(10) if c77[i] == 7] + [1, 3, 7, 9] + """ + rv = defaultdict(int, multiset(digits(n, b)).items()) + rv.pop(b) if b in rv else rv.pop(-b) # b or -b is there + return rv + + +def is_palindromic(n, b=10): + """return True if ``n`` is the same when read from left to right + or right to left in the given base, ``b``. + + Examples + ======== + + >>> from sympy.ntheory import is_palindromic + + >>> all(is_palindromic(i) for i in (-11, 1, 22, 121)) + True + + The second argument allows you to test numbers in other + bases. For example, 88 is palindromic in base-10 but not + in base-8: + + >>> is_palindromic(88, 8) + False + + On the other hand, a number can be palindromic in base-8 but + not in base-10: + + >>> 0o121, is_palindromic(0o121) + (81, False) + + Or it might be palindromic in both bases: + + >>> oct(121), is_palindromic(121, 8) and is_palindromic(121) + ('0o171', True) + + """ + return _palindromic(digits(n, b), 1) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/ecm.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/ecm.py new file mode 100644 index 0000000000000000000000000000000000000000..e854b29f5ecebdfc20c9cddf8c3e06b6ad92b247 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/ecm.py @@ -0,0 +1,326 @@ +from sympy.ntheory import sieve, isprime +from sympy.core.numbers import mod_inverse +from sympy.core.power import integer_log +from sympy.utilities.misc import as_int +import random + +rgen = random.Random() + +#----------------------------------------------------------------------------# +# # +# Lenstra's Elliptic Curve Factorization # +# # +#----------------------------------------------------------------------------# + + +class Point: + """Montgomery form of Points in an elliptic curve. + In this form, the addition and doubling of points + does not need any y-coordinate information thus + decreasing the number of operations. + Using Montgomery form we try to perform point addition + and doubling in least amount of multiplications. + + The elliptic curve used here is of the form + (E : b*y**2*z = x**3 + a*x**2*z + x*z**2). + The a_24 parameter is equal to (a + 2)/4. + + References + ========== + + .. [1] https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf + """ + + def __init__(self, x_cord, z_cord, a_24, mod): + """ + Initial parameters for the Point class. + + Parameters + ========== + + x_cord : X coordinate of the Point + z_cord : Z coordinate of the Point + a_24 : Parameter of the elliptic curve in Montgomery form + mod : modulus + """ + self.x_cord = x_cord + self.z_cord = z_cord + self.a_24 = a_24 + self.mod = mod + + def __eq__(self, other): + """Two points are equal if X/Z of both points are equal + """ + if self.a_24 != other.a_24 or self.mod != other.mod: + return False + return self.x_cord * other.z_cord % self.mod ==\ + other.x_cord * self.z_cord % self.mod + + def add(self, Q, diff): + """ + Add two points self and Q where diff = self - Q. Moreover the assumption + is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm + requires 6 multiplications. Here the difference between the points + is already known and using this algorithm speeds up the addition + by reducing the number of multiplication required. Also in the + mont_ladder algorithm is constructed in a way so that the difference + between intermediate points is always equal to the initial point. + So, we always know what the difference between the point is. + + + Parameters + ========== + + Q : point on the curve in Montgomery form + diff : self - Q + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p2 = Point(13, 10, 7, 29) + >>> p3 = p2.add(p1, p1) + >>> p3.x_cord + 23 + >>> p3.z_cord + 17 + """ + u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord) + v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord) + add, subt = u + v, u - v + x_cord = diff.z_cord * add * add % self.mod + z_cord = diff.x_cord * subt * subt % self.mod + return Point(x_cord, z_cord, self.a_24, self.mod) + + def double(self): + """ + Doubles a point in an elliptic curve in Montgomery form. + This algorithm requires 5 multiplications. + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p2 = p1.double() + >>> p2.x_cord + 13 + >>> p2.z_cord + 10 + """ + u = pow(self.x_cord + self.z_cord, 2, self.mod) + v = pow(self.x_cord - self.z_cord, 2, self.mod) + diff = u - v + x_cord = u*v % self.mod + z_cord = diff*(v + self.a_24*diff) % self.mod + return Point(x_cord, z_cord, self.a_24, self.mod) + + def mont_ladder(self, k): + """ + Scalar multiplication of a point in Montgomery form + using Montgomery Ladder Algorithm. + A total of 11 multiplications are required in each step of this + algorithm. + + Parameters + ========== + + k : The positive integer multiplier + + Examples + ======== + + >>> from sympy.ntheory.ecm import Point + >>> p1 = Point(11, 16, 7, 29) + >>> p3 = p1.mont_ladder(3) + >>> p3.x_cord + 23 + >>> p3.z_cord + 17 + """ + Q = self + R = self.double() + for i in bin(k)[3:]: + if i == '1': + Q = R.add(Q, self) + R = R.double() + else: + R = Q.add(R, self) + Q = Q.double() + return Q + + +def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): + """Returns one factor of n using + Lenstra's 2 Stage Elliptic curve Factorization + with Suyama's Parameterization. Here Montgomery + arithmetic is used for fast computation of addition + and doubling of points in elliptic curve. + + This ECM method considers elliptic curves in Montgomery + form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves + elliptic curve operations (mod N), where the elements in + Z are reduced (mod N). Since N is not a prime, E over FF(N) + is not really an elliptic curve but we can still do point additions + and doubling as if FF(N) was a field. + + Stage 1 : The basic algorithm involves taking a random point (P) on an + elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. + Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, + might be a smooth number that divides k. Then we have k = l * |E(FF(q))| + for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, + hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn + factor of N (q) can be recovered by taking gcd(kP.z_cord, N). + + Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize + the fact that even if kP != 0, the value of k might miss just one large + prime divisor of |E(FF(q))|. In this case we only need to compute the + scalar multiplication by p to get p*k*P = O. Here a second bound B2 + restrict the size of possible values of p. + + Parameters + ========== + + n : Number to be Factored + B1 : Stage 1 Bound + B2 : Stage 2 Bound + max_curve : Maximum number of curves generated + + References + ========== + + .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: + A Computational Perspective" (2nd Ed.), page 344 + """ + n = as_int(n) + if B1 % 2 != 0 or B2 % 2 != 0: + raise ValueError("The Bounds should be an even integer") + sieve.extend(B2) + + if isprime(n): + return n + + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.polys.polytools import gcd + D = int(sqrt(B2)) + beta = [0]*(D + 1) + S = [0]*(D + 1) + k = 1 + for p in sieve.primerange(1, B1 + 1): + k *= pow(p, integer_log(B1, p)[0]) + for _ in range(max_curve): + #Suyama's Parametrization + sigma = rgen.randint(6, n - 1) + u = (sigma*sigma - 5) % n + v = (4*sigma) % n + u_3 = pow(u, 3, n) + + try: + # We use the elliptic curve y**2 = x**3 + a*x**2 + x + # where a = pow(v - u, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2 + # However, we do not declare a because it is more convenient + # to use a24 = (a + 2)*mod_inverse(4, n) in the calculation. + a24 = pow(v - u, 3, n)*(3*u + v)*mod_inverse(16*u_3*v, n) % n + except ValueError: + #If the mod_inverse(16*u_3*v, n) doesn't exist (i.e., g != 1) + g = gcd(16*u_3*v, n) + #If g = n, try another curve + if g == n: + continue + return g + + Q = Point(u_3, pow(v, 3, n), a24, n) + Q = Q.mont_ladder(k) + g = gcd(Q.z_cord, n) + + #Stage 1 factor + if g != 1 and g != n: + return g + #Stage 1 failure. Q.z = 0, Try another curve + elif g == n: + continue + + #Stage 2 - Improved Standard Continuation + S[1] = Q.double() + S[2] = S[1].double() + beta[1] = (S[1].x_cord*S[1].z_cord) % n + beta[2] = (S[2].x_cord*S[2].z_cord) % n + + for d in range(3, D + 1): + S[d] = S[d - 1].add(S[1], S[d - 2]) + beta[d] = (S[d].x_cord*S[d].z_cord) % n + + g = 1 + B = B1 - 1 + T = Q.mont_ladder(B - 2*D) + R = Q.mont_ladder(B) + + for r in range(B, B2, 2*D): + alpha = (R.x_cord*R.z_cord) % n + for q in sieve.primerange(r + 2, r + 2*D + 1): + delta = (q - r) // 2 + # We want to calculate + # f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord + f = (R.x_cord - S[delta].x_cord)*\ + (R.z_cord + S[delta].z_cord) - alpha + beta[delta] + g = (g*f) % n + #Swap + T, R = R, R.add(S[D], T) + g = gcd(n, g) + + #Stage 2 Factor found + if g != 1 and g != n: + return g + + #ECM failed, Increase the bounds + raise ValueError("Increase the bounds") + + +def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234): + """Performs factorization using Lenstra's Elliptic curve method. + + This function repeatedly calls `ecm_one_factor` to compute the factors + of n. First all the small factors are taken out using trial division. + Then `ecm_one_factor` is used to compute one factor at a time. + + Parameters + ========== + + n : Number to be Factored + B1 : Stage 1 Bound + B2 : Stage 2 Bound + max_curve : Maximum number of curves generated + seed : Initialize pseudorandom generator + + Examples + ======== + + >>> from sympy.ntheory import ecm + >>> ecm(25645121643901801) + {5394769, 4753701529} + >>> ecm(9804659461513846513) + {4641991, 2112166839943} + """ + _factors = set() + for prime in sieve.primerange(1, 100000): + if n % prime == 0: + _factors.add(prime) + while(n % prime == 0): + n //= prime + rgen.seed(seed) + while(n > 1): + try: + factor = _ecm_one_factor(n, B1, B2, max_curve) + except ValueError: + raise ValueError("Increase the bounds") + _factors.add(factor) + n //= factor + + factors = set() + for factor in _factors: + if isprime(factor): + factors.add(factor) + continue + factors |= ecm(factor) + return factors diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..8a42540b372042f596808684fef8e3fc57935b74 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py @@ -0,0 +1,223 @@ +from sympy.core.containers import Tuple +from sympy.core.numbers import (Integer, Rational) +from sympy.core.singleton import S +import sympy.polys + +from math import gcd + + +def egyptian_fraction(r, algorithm="Greedy"): + """ + Return the list of denominators of an Egyptian fraction + expansion [1]_ of the said rational `r`. + + Parameters + ========== + + r : Rational or (p, q) + a positive rational number, ``p/q``. + algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional + Denotes the algorithm to be used (the default is "Greedy"). + + Examples + ======== + + >>> from sympy import Rational + >>> from sympy.ntheory.egyptian_fraction import egyptian_fraction + >>> egyptian_fraction(Rational(3, 7)) + [3, 11, 231] + >>> egyptian_fraction((3, 7), "Graham Jewett") + [7, 8, 9, 56, 57, 72, 3192] + >>> egyptian_fraction((3, 7), "Takenouchi") + [4, 7, 28] + >>> egyptian_fraction((3, 7), "Golomb") + [3, 15, 35] + >>> egyptian_fraction((11, 5), "Golomb") + [1, 2, 3, 4, 9, 234, 1118, 2580] + + See Also + ======== + + sympy.core.numbers.Rational + + Notes + ===== + + Currently the following algorithms are supported: + + 1) Greedy Algorithm + + Also called the Fibonacci-Sylvester algorithm [2]_. + At each step, extract the largest unit fraction less + than the target and replace the target with the remainder. + + It has some distinct properties: + + a) Given `p/q` in lowest terms, generates an expansion of maximum + length `p`. Even as the numerators get large, the number of + terms is seldom more than a handful. + + b) Uses minimal memory. + + c) The terms can blow up (standard examples of this are 5/121 and + 31/311). The denominator is at most squared at each step + (doubly-exponential growth) and typically exhibits + singly-exponential growth. + + 2) Graham Jewett Algorithm + + The algorithm suggested by the result of Graham and Jewett. + Note that this has a tendency to blow up: the length of the + resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_. + + 3) Takenouchi Algorithm + + The algorithm suggested by Takenouchi (1921). + Differs from the Graham-Jewett algorithm only in the handling + of duplicates. See [3]_. + + 4) Golomb's Algorithm + + A method given by Golumb (1962), using modular arithmetic and + inverses. It yields the same results as a method using continued + fractions proposed by Bleicher (1972). See [4]_. + + If the given rational is greater than or equal to 1, a greedy algorithm + of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking + all the unit fractions of this sequence until adding one more would be + greater than the given number. This list of denominators is prefixed + to the result from the requested algorithm used on the remainder. For + example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4, + 5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5, + 6, 7] is part of the harmonic sequence summing to 363/140, leaving a + remainder of 31/420, which yields [14, 420] by the Greedy algorithm. + The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3, + 4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Egyptian_fraction + .. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions + .. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html + .. [4] https://web.archive.org/web/20180413004012/https://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf + + """ + + if not isinstance(r, Rational): + if isinstance(r, (Tuple, tuple)) and len(r) == 2: + r = Rational(*r) + else: + raise ValueError("Value must be a Rational or tuple of ints") + if r <= 0: + raise ValueError("Value must be positive") + + # common cases that all methods agree on + x, y = r.as_numer_denom() + if y == 1 and x == 2: + return [Integer(i) for i in [1, 2, 3, 6]] + if x == y + 1: + return [S.One, y] + + prefix, rem = egypt_harmonic(r) + if rem == 0: + return prefix + # work in Python ints + x, y = rem.p, rem.q + # assert x < y and gcd(x, y) = 1 + + if algorithm == "Greedy": + postfix = egypt_greedy(x, y) + elif algorithm == "Graham Jewett": + postfix = egypt_graham_jewett(x, y) + elif algorithm == "Takenouchi": + postfix = egypt_takenouchi(x, y) + elif algorithm == "Golomb": + postfix = egypt_golomb(x, y) + else: + raise ValueError("Entered invalid algorithm") + return prefix + [Integer(i) for i in postfix] + + +def egypt_greedy(x, y): + # assumes gcd(x, y) == 1 + if x == 1: + return [y] + else: + a = (-y) % x + b = y*(y//x + 1) + c = gcd(a, b) + if c > 1: + num, denom = a//c, b//c + else: + num, denom = a, b + return [y//x + 1] + egypt_greedy(num, denom) + + +def egypt_graham_jewett(x, y): + # assumes gcd(x, y) == 1 + l = [y] * x + + # l is now a list of integers whose reciprocals sum to x/y. + # we shall now proceed to manipulate the elements of l without + # changing the reciprocated sum until all elements are unique. + + while len(l) != len(set(l)): + l.sort() # so the list has duplicates. find a smallest pair + for i in range(len(l) - 1): + if l[i] == l[i + 1]: + break + # we have now identified a pair of identical + # elements: l[i] and l[i + 1]. + # now comes the application of the result of graham and jewett: + l[i + 1] = l[i] + 1 + # and we just iterate that until the list has no duplicates. + l.append(l[i]*(l[i] + 1)) + return sorted(l) + + +def egypt_takenouchi(x, y): + # assumes gcd(x, y) == 1 + # special cases for 3/y + if x == 3: + if y % 2 == 0: + return [y//2, y] + i = (y - 1)//2 + j = i + 1 + k = j + i + return [j, k, j*k] + l = [y] * x + while len(l) != len(set(l)): + l.sort() + for i in range(len(l) - 1): + if l[i] == l[i + 1]: + break + k = l[i] + if k % 2 == 0: + l[i] = l[i] // 2 + del l[i + 1] + else: + l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2 + return sorted(l) + + +def egypt_golomb(x, y): + # assumes x < y and gcd(x, y) == 1 + if x == 1: + return [y] + xp = sympy.polys.ZZ.invert(int(x), int(y)) + rv = [xp*y] + rv.extend(egypt_golomb((x*xp - 1)//y, xp)) + return sorted(rv) + + +def egypt_harmonic(r): + # assumes r is Rational + rv = [] + d = S.One + acc = S.Zero + while acc + 1/d <= r: + acc += 1/d + rv.append(d) + d += 1 + return (rv, r - acc) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..b9cdbcd870ecff6255cbd238b8fb22dde040a6c5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py @@ -0,0 +1,398 @@ +from sympy.core.numbers import oo +from sympy.core.relational import Eq +from sympy.core.symbol import symbols +from sympy.polys.domains import FiniteField, QQ, RationalField, FF +from sympy.solvers.solvers import solve +from sympy.utilities.iterables import is_sequence +from sympy.utilities.misc import as_int +from .factor_ import divisors +from .residue_ntheory import polynomial_congruence + + + +class EllipticCurve: + """ + Create the following Elliptic Curve over domain. + + `y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}` + + The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``, + it create curve as following form. + + `y^{2} = x^{3} + a_{4} x + a_{6}` + + Examples + ======== + + References + ========== + + .. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition + .. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html + .. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition + + """ + + def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus = 0): + if modulus == 0: + domain = QQ + else: + domain = FF(modulus) + a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6)) + self._domain = domain + self.modulus = modulus + # Calculate discriminant + b2 = a1**2 + 4 * a2 + b4 = 2 * a4 + a1 * a3 + b6 = a3**2 + 4 * a6 + b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2 + self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8 + self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6 + self._a1 = a1 + self._a2 = a2 + self._a3 = a3 + self._a4 = a4 + self._a6 = a6 + x, y, z = symbols('x y z') + self.x, self.y, self.z = x, y, z + self._eq = Eq(y**2*z + a1*x*y*z + a3*y*z**2, x**3 + a2*x**2*z + a4*x*z**2 + a6*z**3) + if isinstance(self._domain, FiniteField): + self._rank = 0 + elif isinstance(self._domain, RationalField): + self._rank = None + + def __call__(self, x, y, z=1): + return EllipticCurvePoint(x, y, z, self) + + def __contains__(self, point): + if is_sequence(point): + if len(point) == 2: + z1 = 1 + else: + z1 = point[2] + x1, y1 = point[:2] + elif isinstance(point, EllipticCurvePoint): + x1, y1, z1 = point.x, point.y, point.z + else: + raise ValueError('Invalid point.') + if self.characteristic == 0 and z1 == 0: + return True + return self._eq.subs({self.x: x1, self.y: y1, self.z: z1}) + + def __repr__(self): + return 'E({}): {}'.format(self._domain, self._eq) + + def minimal(self): + """ + Return minimal Weierstrass equation. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + + >>> e1 = EllipticCurve(-10, -20, 0, -1, 1) + >>> e1.minimal() + E(QQ): Eq(y**2*z, x**3 - 13392*x*z**2 - 1080432*z**3) + + """ + char = self.characteristic + if char == 2: + return self + if char == 3: + return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus) + c4 = self._b2**2 - 24*self._b4 + c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6 + return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus) + + def points(self): + """ + Return points of curve over Finite Field. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5) + >>> e2.points() + {(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)} + + """ + + char = self.characteristic + all_pt = set() + if char >= 1: + for i in range(char): + congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: i, self.z: 1})) + sol = polynomial_congruence(congruence_eq, char) + for num in sol: + all_pt.add((i, num)) + return all_pt + else: + raise ValueError("Infinitely many points") + + def points_x(self, x): + "Returns points on with curve where xcoordinate = x" + pt = [] + if self._domain == QQ: + for y in solve(self._eq.subs(self.x, x)): + pt.append((x, y)) + congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: x, self.z: 1})) + for y in polynomial_congruence(congruence_eq, self.characteristic): + pt.append((x, y)) + return pt + + def torsion_points(self): + """ + Return torsion points of curve over Rational number. + + Return point objects those are finite order. + According to Nagell-Lutz theorem, torsion point p(x, y) + x and y are integers, either y = 0 or y**2 is divisor + of discriminent. According to Mazur's theorem, there are + at most 15 points in torsion collection. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e2 = EllipticCurve(-43, 166) + >>> sorted(e2.torsion_points()) + [(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)] + + """ + if self.characteristic > 0: + raise ValueError("No torsion point for Finite Field.") + l = [EllipticCurvePoint.point_at_infinity(self)] + for xx in solve(self._eq.subs({self.y: 0, self.z: 1})): + if xx.is_rational: + l.append(self(xx, 0)) + for i in divisors(self.discriminant, generator=True): + j = int(i**.5) + if j**2 == i: + for xx in solve(self._eq.subs({self.y: j, self.z: 1})): + if not xx.is_rational: + continue + p = self(xx, j) + if p.order() != oo: + l.extend([p, -p]) + return l + + @property + def characteristic(self): + """ + Return domain characteristic. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e2 = EllipticCurve(-43, 166) + >>> e2.characteristic + 0 + + """ + return self._domain.characteristic() + + @property + def discriminant(self): + """ + Return curve discriminant. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e2 = EllipticCurve(0, 17) + >>> e2.discriminant + -124848 + + """ + return int(self._discrim) + + @property + def is_singular(self): + """ + Return True if curve discriminant is equal to zero. + """ + return self.discriminant == 0 + + @property + def j_invariant(self): + """ + Return curve j-invariant. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e1 = EllipticCurve(-2, 0, 0, 1, 1) + >>> e1.j_invariant + 1404928/389 + + """ + c4 = self._b2**2 - 24*self._b4 + return self._domain.to_sympy(c4**3 / self._discrim) + + @property + def order(self): + """ + Number of points in Finite field. + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e2 = EllipticCurve(1, 0, modulus=19) + >>> e2.order + 19 + + """ + if self.characteristic == 0: + raise NotImplementedError("Still not implemented") + return len(self.points()) + + @property + def rank(self): + """ + Number of independent points of infinite order. + + For Finite field, it must be 0. + """ + if self._rank is not None: + return self._rank + raise NotImplementedError("Still not implemented") + + +class EllipticCurvePoint: + """ + Point of Elliptic Curve + + Examples + ======== + + >>> from sympy.ntheory.elliptic_curve import EllipticCurve + >>> e1 = EllipticCurve(-17, 16) + >>> p1 = e1(0, -4, 1) + >>> p2 = e1(1, 0) + >>> p1 + p2 + (15, -56) + >>> e3 = EllipticCurve(-1, 9) + >>> e3(1, -3) * 3 + (664/169, 17811/2197) + >>> (e3(1, -3) * 3).order() + oo + >>> e2 = EllipticCurve(-2, 0, 0, 1, 1) + >>> p = e2(-1,1) + >>> q = e2(0, -1) + >>> p+q + (4, 8) + >>> p-q + (1, 0) + >>> 3*p-5*q + (328/361, -2800/6859) + """ + + @staticmethod + def point_at_infinity(curve): + return EllipticCurvePoint(0, 1, 0, curve) + + def __init__(self, x, y, z, curve): + dom = curve._domain.convert + self.x = dom(x) + self.y = dom(y) + self.z = dom(z) + self._curve = curve + self._domain = self._curve._domain + if not self._curve.__contains__(self): + raise ValueError("The curve does not contain this point") + + def __add__(self, p): + if self.z == 0: + return p + if p.z == 0: + return self + x1, y1 = self.x/self.z, self.y/self.z + x2, y2 = p.x/p.z, p.y/p.z + a1 = self._curve._a1 + a2 = self._curve._a2 + a3 = self._curve._a3 + a4 = self._curve._a4 + a6 = self._curve._a6 + if x1 != x2: + slope = (y1 - y2) / (x1 - x2) + yint = (y1 * x2 - y2 * x1) / (x2 - x1) + else: + if (y1 + y2) == 0: + return self.point_at_infinity(self._curve) + slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1) + yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1) + x3 = slope**2 + a1*slope - a2 - x1 - x2 + y3 = -(slope + a1) * x3 - yint - a3 + return self._curve(x3, y3, 1) + + def __lt__(self, other): + return (self.x, self.y, self.z) < (other.x, other.y, other.z) + + def __mul__(self, n): + n = as_int(n) + r = self.point_at_infinity(self._curve) + if n == 0: + return r + if n < 0: + return -self * -n + p = self + while n: + if n & 1: + r = r + p + n >>= 1 + p = p + p + return r + + def __rmul__(self, n): + return self * n + + def __neg__(self): + return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve) + + def __repr__(self): + if self.z == 0: + return 'O' + dom = self._curve._domain + try: + return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y)) + except TypeError: + pass + return '({}, {})'.format(self.x, self.y) + + def __sub__(self, other): + return self.__add__(-other) + + def order(self): + """ + Return point order n where nP = 0. + + """ + if self.z == 0: + return 1 + if self.y == 0: # P = -P + return 2 + p = self * 2 + if p.y == -self.y: # 2P = -P + return 3 + i = 2 + if self._domain != QQ: + while int(p.x) == p.x and int(p.y) == p.y: + p = self + p + i += 1 + if p.z == 0: + return i + return oo + while p.x.numerator == p.x and p.y.numerator == p.y: + p = self + p + i += 1 + if i > 12: + return oo + if p.z == 0: + return i + return oo diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/factor_.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/factor_.py new file mode 100644 index 0000000000000000000000000000000000000000..67e1242dcced325578e0d7469b585ff41a1c2ed6 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/factor_.py @@ -0,0 +1,2654 @@ +""" +Integer factorization +""" + +from collections import defaultdict +from functools import reduce +import random +import math + +from sympy.core import sympify +from sympy.core.containers import Dict +from sympy.core.evalf import bitcount +from sympy.core.expr import Expr +from sympy.core.function import Function +from sympy.core.logic import fuzzy_and +from sympy.core.mul import Mul +from sympy.core.numbers import igcd, ilcm, Rational, Integer +from sympy.core.power import integer_nthroot, Pow, integer_log +from sympy.core.singleton import S +from sympy.external.gmpy import SYMPY_INTS +from .primetest import isprime +from .generate import sieve, primerange, nextprime +from .digits import digits +from sympy.utilities.iterables import flatten +from sympy.utilities.misc import as_int, filldedent +from .ecm import _ecm_one_factor + +# Note: This list should be updated whenever new Mersenne primes are found. +# Refer: https://www.mersenne.org/ +MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, + 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, + 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, + 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933) + +# compute more when needed for i in Mersenne prime exponents +PERFECT = [6] # 2**(i-1)*(2**i-1) +MERSENNES = [3] # 2**i - 1 + + +def _ismersenneprime(n): + global MERSENNES + j = len(MERSENNES) + while n > MERSENNES[-1] and j < len(MERSENNE_PRIME_EXPONENTS): + # conservatively grow the list + MERSENNES.append(2**MERSENNE_PRIME_EXPONENTS[j] - 1) + j += 1 + return n in MERSENNES + + +def _isperfect(n): + global PERFECT + if n % 2 == 0: + j = len(PERFECT) + while n > PERFECT[-1] and j < len(MERSENNE_PRIME_EXPONENTS): + # conservatively grow the list + t = 2**(MERSENNE_PRIME_EXPONENTS[j] - 1) + PERFECT.append(t*(2*t - 1)) + j += 1 + return n in PERFECT + + +small_trailing = [0] * 256 +for j in range(1,8): + small_trailing[1<>> from sympy.ntheory.factor_ import smoothness + >>> smoothness(2**7*3**2) + (3, 128) + >>> smoothness(2**4*13) + (13, 16) + >>> smoothness(2) + (2, 2) + + See Also + ======== + + factorint, smoothness_p + """ + + if n == 1: + return (1, 1) # not prime, but otherwise this causes headaches + facs = factorint(n) + return max(facs), max(m**facs[m] for m in facs) + + +def smoothness_p(n, m=-1, power=0, visual=None): + """ + Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...] + where: + + 1. p**M is the base-p divisor of n + 2. sm(p + m) is the smoothness of p + m (m = -1 by default) + 3. psm(p + m) is the power smoothness of p + m + + The list is sorted according to smoothness (default) or by power smoothness + if power=1. + + The smoothness of the numbers to the left (m = -1) or right (m = 1) of a + factor govern the results that are obtained from the p +/- 1 type factoring + methods. + + >>> from sympy.ntheory.factor_ import smoothness_p, factorint + >>> smoothness_p(10431, m=1) + (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) + >>> smoothness_p(10431) + (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) + >>> smoothness_p(10431, power=1) + (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) + + If visual=True then an annotated string will be returned: + + >>> print(smoothness_p(21477639576571, visual=1)) + p**i=4410317**1 has p-1 B=1787, B-pow=1787 + p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 + + This string can also be generated directly from a factorization dictionary + and vice versa: + + >>> factorint(17*9) + {3: 2, 17: 1} + >>> smoothness_p(_) + 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16' + >>> smoothness_p(_) + {3: 2, 17: 1} + + The table of the output logic is: + + ====== ====== ======= ======= + | Visual + ------ ---------------------- + Input True False other + ====== ====== ======= ======= + dict str tuple str + str str tuple dict + tuple str tuple str + n str tuple tuple + mul str tuple tuple + ====== ====== ======= ======= + + See Also + ======== + + factorint, smoothness + """ + + # visual must be True, False or other (stored as None) + if visual in (1, 0): + visual = bool(visual) + elif visual not in (True, False): + visual = None + + if isinstance(n, str): + if visual: + return n + d = {} + for li in n.splitlines(): + k, v = [int(i) for i in + li.split('has')[0].split('=')[1].split('**')] + d[k] = v + if visual is not True and visual is not False: + return d + return smoothness_p(d, visual=False) + elif not isinstance(n, tuple): + facs = factorint(n, visual=False) + + if power: + k = -1 + else: + k = 1 + if isinstance(n, tuple): + rv = n + else: + rv = (m, sorted([(f, + tuple([M] + list(smoothness(f + m)))) + for f, M in list(facs.items())], + key=lambda x: (x[1][k], x[0]))) + + if visual is False or (visual is not True) and (type(n) in [int, Mul]): + return rv + lines = [] + for dat in rv[1]: + dat = flatten(dat) + dat.insert(2, m) + lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat)) + return '\n'.join(lines) + + +def trailing(n): + """Count the number of trailing zero digits in the binary + representation of n, i.e. determine the largest power of 2 + that divides n. + + Examples + ======== + + >>> from sympy import trailing + >>> trailing(128) + 7 + >>> trailing(63) + 0 + """ + n = abs(int(n)) + if not n: + return 0 + low_byte = n & 0xff + if low_byte: + return small_trailing[low_byte] + + # 2**m is quick for z up through 2**30 + z = bitcount(n) - 1 + if isinstance(z, SYMPY_INTS): + if n == 1 << z: + return z + + if z < 300: + # fixed 8-byte reduction + t = 8 + n >>= 8 + while not n & 0xff: + n >>= 8 + t += 8 + return t + small_trailing[n & 0xff] + + # binary reduction important when there might be a large + # number of trailing 0s + t = 0 + p = 8 + while not n & 1: + while not n & ((1 << p) - 1): + n >>= p + t += p + p *= 2 + p //= 2 + return t + + +def multiplicity(p, n): + """ + Find the greatest integer m such that p**m divides n. + + Examples + ======== + + >>> from sympy import multiplicity, Rational + >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]] + [0, 1, 2, 3, 3] + >>> multiplicity(3, Rational(1, 9)) + -2 + + Note: when checking for the multiplicity of a number in a + large factorial it is most efficient to send it as an unevaluated + factorial or to call ``multiplicity_in_factorial`` directly: + + >>> from sympy.ntheory import multiplicity_in_factorial + >>> from sympy import factorial + >>> p = factorial(25) + >>> n = 2**100 + >>> nfac = factorial(n, evaluate=False) + >>> multiplicity(p, nfac) + 52818775009509558395695966887 + >>> _ == multiplicity_in_factorial(p, n) + True + + """ + try: + p, n = as_int(p), as_int(n) + except ValueError: + from sympy.functions.combinatorial.factorials import factorial + if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)): + p = Rational(p) + n = Rational(n) + if p.q == 1: + if n.p == 1: + return -multiplicity(p.p, n.q) + return multiplicity(p.p, n.p) - multiplicity(p.p, n.q) + elif p.p == 1: + return multiplicity(p.q, n.q) + else: + like = min( + multiplicity(p.p, n.p), + multiplicity(p.q, n.q)) + cross = min( + multiplicity(p.q, n.p), + multiplicity(p.p, n.q)) + return like - cross + elif (isinstance(p, (SYMPY_INTS, Integer)) and + isinstance(n, factorial) and + isinstance(n.args[0], Integer) and + n.args[0] >= 0): + return multiplicity_in_factorial(p, n.args[0]) + raise ValueError('expecting ints or fractions, got %s and %s' % (p, n)) + + if n == 0: + raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n)) + if p == 2: + return trailing(n) + if p < 2: + raise ValueError('p must be an integer, 2 or larger, but got %s' % p) + if p == n: + return 1 + + m = 0 + n, rem = divmod(n, p) + while not rem: + m += 1 + if m > 5: + # The multiplicity could be very large. Better + # to increment in powers of two + e = 2 + while 1: + ppow = p**e + if ppow < n: + nnew, rem = divmod(n, ppow) + if not rem: + m += e + e *= 2 + n = nnew + continue + return m + multiplicity(p, n) + n, rem = divmod(n, p) + return m + + +def multiplicity_in_factorial(p, n): + """return the largest integer ``m`` such that ``p**m`` divides ``n!`` + without calculating the factorial of ``n``. + + + Examples + ======== + + >>> from sympy.ntheory import multiplicity_in_factorial + >>> from sympy import factorial + + >>> multiplicity_in_factorial(2, 3) + 1 + + An instructive use of this is to tell how many trailing zeros + a given factorial has. For example, there are 6 in 25!: + + >>> factorial(25) + 15511210043330985984000000 + >>> multiplicity_in_factorial(10, 25) + 6 + + For large factorials, it is much faster/feasible to use + this function rather than computing the actual factorial: + + >>> multiplicity_in_factorial(factorial(25), 2**100) + 52818775009509558395695966887 + + """ + + p, n = as_int(p), as_int(n) + + if p <= 0: + raise ValueError('expecting positive integer got %s' % p ) + + if n < 0: + raise ValueError('expecting non-negative integer got %s' % n ) + + factors = factorint(p) + + # keep only the largest of a given multiplicity since those + # of a given multiplicity will be goverened by the behavior + # of the largest factor + test = defaultdict(int) + for k, v in factors.items(): + test[v] = max(k, test[v]) + keep = set(test.values()) + # remove others from factors + for k in list(factors.keys()): + if k not in keep: + factors.pop(k) + + mp = S.Infinity + for i in factors: + # multiplicity of i in n! is + mi = (n - (sum(digits(n, i)) - i))//(i - 1) + # multiplicity of p in n! depends on multiplicity + # of prime `i` in p, so we floor divide by factors[i] + # and keep it if smaller than the multiplicity of p + # seen so far + mp = min(mp, mi//factors[i]) + + return mp + + +def perfect_power(n, candidates=None, big=True, factor=True): + """ + Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique + perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a + perfect power). A ValueError is raised if ``n`` is not Rational. + + By default, the base is recursively decomposed and the exponents + collected so the largest possible ``e`` is sought. If ``big=False`` + then the smallest possible ``e`` (thus prime) will be chosen. + + If ``factor=True`` then simultaneous factorization of ``n`` is + attempted since finding a factor indicates the only possible root + for ``n``. This is True by default since only a few small factors will + be tested in the course of searching for the perfect power. + + The use of ``candidates`` is primarily for internal use; if provided, + False will be returned if ``n`` cannot be written as a power with one + of the candidates as an exponent and factoring (beyond testing for + a factor of 2) will not be attempted. + + Examples + ======== + + >>> from sympy import perfect_power, Rational + >>> perfect_power(16) + (2, 4) + >>> perfect_power(16, big=False) + (4, 2) + + Negative numbers can only have odd perfect powers: + + >>> perfect_power(-4) + False + >>> perfect_power(-8) + (-2, 3) + + Rationals are also recognized: + + >>> perfect_power(Rational(1, 2)**3) + (1/2, 3) + >>> perfect_power(Rational(-3, 2)**3) + (-3/2, 3) + + Notes + ===== + + To know whether an integer is a perfect power of 2 use + + >>> is2pow = lambda n: bool(n and not n & (n - 1)) + >>> [(i, is2pow(i)) for i in range(5)] + [(0, False), (1, True), (2, True), (3, False), (4, True)] + + It is not necessary to provide ``candidates``. When provided + it will be assumed that they are ints. The first one that is + larger than the computed maximum possible exponent will signal + failure for the routine. + + >>> perfect_power(3**8, [9]) + False + >>> perfect_power(3**8, [2, 4, 8]) + (3, 8) + >>> perfect_power(3**8, [4, 8], big=False) + (9, 4) + + See Also + ======== + sympy.core.power.integer_nthroot + sympy.ntheory.primetest.is_square + """ + if isinstance(n, Rational) and not n.is_Integer: + p, q = n.as_numer_denom() + if p is S.One: + pp = perfect_power(q) + if pp: + pp = (n.func(1, pp[0]), pp[1]) + else: + pp = perfect_power(p) + if pp: + num, e = pp + pq = perfect_power(q, [e]) + if pq: + den, _ = pq + pp = n.func(num, den), e + return pp + + n = as_int(n) + if n < 0: + pp = perfect_power(-n) + if pp: + b, e = pp + if e % 2: + return -b, e + return False + + if n <= 3: + # no unique exponent for 0, 1 + # 2 and 3 have exponents of 1 + return False + logn = math.log(n, 2) + max_possible = int(logn) + 2 # only check values less than this + not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8 + min_possible = 2 + not_square + if not candidates: + candidates = primerange(min_possible, max_possible) + else: + candidates = sorted([i for i in candidates + if min_possible <= i < max_possible]) + if n%2 == 0: + e = trailing(n) + candidates = [i for i in candidates if e%i == 0] + if big: + candidates = reversed(candidates) + for e in candidates: + r, ok = integer_nthroot(n, e) + if ok: + return (r, e) + return False + + def _factors(): + rv = 2 + n % 2 + while True: + yield rv + rv = nextprime(rv) + + for fac, e in zip(_factors(), candidates): + # see if there is a factor present + if factor and n % fac == 0: + # find what the potential power is + if fac == 2: + e = trailing(n) + else: + e = multiplicity(fac, n) + # if it's a trivial power we are done + if e == 1: + return False + + # maybe the e-th root of n is exact + r, exact = integer_nthroot(n, e) + if not exact: + # Having a factor, we know that e is the maximal + # possible value for a root of n. + # If n = fac**e*m can be written as a perfect + # power then see if m can be written as r**E where + # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E + m = n//fac**e + rE = perfect_power(m, candidates=divisors(e, generator=True)) + if not rE: + return False + else: + r, E = rE + r, e = fac**(e//E)*r, E + if not big: + e0 = primefactors(e) + if e0[0] != e: + r, e = r**(e//e0[0]), e0[0] + return r, e + + # Weed out downright impossible candidates + if logn/e < 40: + b = 2.0**(logn/e) + if abs(int(b + 0.5) - b) > 0.01: + continue + + # now see if the plausible e makes a perfect power + r, exact = integer_nthroot(n, e) + if exact: + if big: + m = perfect_power(r, big=big, factor=factor) + if m: + r, e = m[0], e*m[1] + return int(r), e + + return False + + +def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None): + r""" + Use Pollard's rho method to try to extract a nontrivial factor + of ``n``. The returned factor may be a composite number. If no + factor is found, ``None`` is returned. + + The algorithm generates pseudo-random values of x with a generator + function, replacing x with F(x). If F is not supplied then the + function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``. + Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be + supplied; the ``a`` will be ignored if F was supplied. + + The sequence of numbers generated by such functions generally have a + a lead-up to some number and then loop around back to that number and + begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader + and loop look a bit like the Greek letter rho, and thus the name, 'rho'. + + For a given function, very different leader-loop values can be obtained + so it is a good idea to allow for retries: + + >>> from sympy.ntheory.generate import cycle_length + >>> n = 16843009 + >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n + >>> for s in range(5): + ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s))) + ... + loop length = 2489; leader length = 42 + loop length = 78; leader length = 120 + loop length = 1482; leader length = 99 + loop length = 1482; leader length = 285 + loop length = 1482; leader length = 100 + + Here is an explicit example where there is a two element leadup to + a sequence of 3 numbers (11, 14, 4) that then repeat: + + >>> x=2 + >>> for i in range(9): + ... x=(x**2+12)%17 + ... print(x) + ... + 16 + 13 + 11 + 14 + 4 + 11 + 14 + 4 + 11 + >>> next(cycle_length(lambda x: (x**2+12)%17, 2)) + (3, 2) + >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True)) + [16, 13, 11, 14, 4] + + Instead of checking the differences of all generated values for a gcd + with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd, + 2nd and 4th, 3rd and 6th until it has been detected that the loop has been + traversed. Loops may be many thousands of steps long before rho finds a + factor or reports failure. If ``max_steps`` is specified, the iteration + is cancelled with a failure after the specified number of steps. + + Examples + ======== + + >>> from sympy import pollard_rho + >>> n=16843009 + >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n + >>> pollard_rho(n, F=F) + 257 + + Use the default setting with a bad value of ``a`` and no retries: + + >>> pollard_rho(n, a=n-2, retries=0) + + If retries is > 0 then perhaps the problem will correct itself when + new values are generated for a: + + >>> pollard_rho(n, a=n-2, retries=1) + 257 + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 229-231 + + """ + n = int(n) + if n < 5: + raise ValueError('pollard_rho should receive n > 4') + prng = random.Random(seed + retries) + V = s + for i in range(retries + 1): + U = V + if not F: + F = lambda x: (pow(x, 2, n) + a) % n + j = 0 + while 1: + if max_steps and (j > max_steps): + break + j += 1 + U = F(U) + V = F(F(V)) # V is 2x further along than U + g = igcd(U - V, n) + if g == 1: + continue + if g == n: + break + return int(g) + V = prng.randint(0, n - 1) + a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2 + F = None + return None + + +def pollard_pm1(n, B=10, a=2, retries=0, seed=1234): + """ + Use Pollard's p-1 method to try to extract a nontrivial factor + of ``n``. Either a divisor (perhaps composite) or ``None`` is returned. + + The value of ``a`` is the base that is used in the test gcd(a**M - 1, n). + The default is 2. If ``retries`` > 0 then if no factor is found after the + first attempt, a new ``a`` will be generated randomly (using the ``seed``) + and the process repeated. + + Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)). + + A search is made for factors next to even numbers having a power smoothness + less than ``B``. Choosing a larger B increases the likelihood of finding a + larger factor but takes longer. Whether a factor of n is found or not + depends on ``a`` and the power smoothness of the even number just less than + the factor p (hence the name p - 1). + + Although some discussion of what constitutes a good ``a`` some + descriptions are hard to interpret. At the modular.math site referenced + below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1 + for every prime power divisor of N. But consider the following: + + >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1 + >>> n=257*1009 + >>> smoothness_p(n) + (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))]) + + So we should (and can) find a root with B=16: + + >>> pollard_pm1(n, B=16, a=3) + 1009 + + If we attempt to increase B to 256 we find that it does not work: + + >>> pollard_pm1(n, B=256) + >>> + + But if the value of ``a`` is changed we find that only multiples of + 257 work, e.g.: + + >>> pollard_pm1(n, B=256, a=257) + 1009 + + Checking different ``a`` values shows that all the ones that did not + work had a gcd value not equal to ``n`` but equal to one of the + factors: + + >>> from sympy import ilcm, igcd, factorint, Pow + >>> M = 1 + >>> for i in range(2, 256): + ... M = ilcm(M, i) + ... + >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if + ... igcd(pow(a, M, n) - 1, n) != n]) + {1009} + + But does aM % d for every divisor of n give 1? + + >>> aM = pow(255, M, n) + >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args] + [(257**1, 1), (1009**1, 1)] + + No, only one of them. So perhaps the principle is that a root will + be found for a given value of B provided that: + + 1) the power smoothness of the p - 1 value next to the root + does not exceed B + 2) a**M % p != 1 for any of the divisors of n. + + By trying more than one ``a`` it is possible that one of them + will yield a factor. + + Examples + ======== + + With the default smoothness bound, this number cannot be cracked: + + >>> from sympy.ntheory import pollard_pm1 + >>> pollard_pm1(21477639576571) + + Increasing the smoothness bound helps: + + >>> pollard_pm1(21477639576571, B=2000) + 4410317 + + Looking at the smoothness of the factors of this number we find: + + >>> from sympy.ntheory.factor_ import smoothness_p, factorint + >>> print(smoothness_p(21477639576571, visual=1)) + p**i=4410317**1 has p-1 B=1787, B-pow=1787 + p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 + + The B and B-pow are the same for the p - 1 factorizations of the divisors + because those factorizations had a very large prime factor: + + >>> factorint(4410317 - 1) + {2: 2, 617: 1, 1787: 1} + >>> factorint(4869863-1) + {2: 1, 2434931: 1} + + Note that until B reaches the B-pow value of 1787, the number is not cracked; + + >>> pollard_pm1(21477639576571, B=1786) + >>> pollard_pm1(21477639576571, B=1787) + 4410317 + + The B value has to do with the factors of the number next to the divisor, + not the divisors themselves. A worst case scenario is that the number next + to the factor p has a large prime divisisor or is a perfect power. If these + conditions apply then the power-smoothness will be about p/2 or p. The more + realistic is that there will be a large prime factor next to p requiring + a B value on the order of p/2. Although primes may have been searched for + up to this level, the p/2 is a factor of p - 1, something that we do not + know. The modular.math reference below states that 15% of numbers in the + range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6 + will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the + percentages are nearly reversed...but in that range the simple trial + division is quite fast. + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 236-238 + .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html + .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf + """ + + n = int(n) + if n < 4 or B < 3: + raise ValueError('pollard_pm1 should receive n > 3 and B > 2') + prng = random.Random(seed + B) + + # computing a**lcm(1,2,3,..B) % n for B > 2 + # it looks weird, but it's right: primes run [2, B] + # and the answer's not right until the loop is done. + for i in range(retries + 1): + aM = a + for p in sieve.primerange(2, B + 1): + e = int(math.log(B, p)) + aM = pow(aM, pow(p, e), n) + g = igcd(aM - 1, n) + if 1 < g < n: + return int(g) + + # get a new a: + # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1' + # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will + # give a zero, too, so we set the range as [2, n-2]. Some references + # say 'a' should be coprime to n, but either will detect factors. + a = prng.randint(2, n - 2) + + +def _trial(factors, n, candidates, verbose=False): + """ + Helper function for integer factorization. Trial factors ``n` + against all integers given in the sequence ``candidates`` + and updates the dict ``factors`` in-place. Returns the reduced + value of ``n`` and a flag indicating whether any factors were found. + """ + if verbose: + factors0 = list(factors.keys()) + nfactors = len(factors) + for d in candidates: + if n % d == 0: + m = multiplicity(d, n) + n //= d**m + factors[d] = m + if verbose: + for k in sorted(set(factors).difference(set(factors0))): + print(factor_msg % (k, factors[k])) + return int(n), len(factors) != nfactors + + +def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1, + verbose): + """ + Helper function for integer factorization. Checks if ``n`` + is a prime or a perfect power, and in those cases updates + the factorization and raises ``StopIteration``. + """ + + if verbose: + print('Check for termination') + + # since we've already been factoring there is no need to do + # simultaneous factoring with the power check + p = perfect_power(n, factor=False) + if p is not False: + base, exp = p + if limitp1: + limit = limitp1 - 1 + else: + limit = limitp1 + facs = factorint(base, limit, use_trial, use_rho, use_pm1, + verbose=False) + for b, e in facs.items(): + if verbose: + print(factor_msg % (b, e)) + factors[b] = exp*e + raise StopIteration + + if isprime(n): + factors[int(n)] = 1 + raise StopIteration + + if n == 1: + raise StopIteration + +trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i" +trial_msg = "Trial division with primes [%i ... %i]" +rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i" +pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i" +ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i" +factor_msg = '\t%i ** %i' +fermat_msg = 'Close factors satisying Fermat condition found.' +complete_msg = 'Factorization is complete.' + + +def _factorint_small(factors, n, limit, fail_max): + """ + Return the value of n and either a 0 (indicating that factorization up + to the limit was complete) or else the next near-prime that would have + been tested. + + Factoring stops if there are fail_max unsuccessful tests in a row. + + If factors of n were found they will be in the factors dictionary as + {factor: multiplicity} and the returned value of n will have had those + factors removed. The factors dictionary is modified in-place. + + """ + + def done(n, d): + """return n, d if the sqrt(n) was not reached yet, else + n, 0 indicating that factoring is done. + """ + if d*d <= n: + return n, d + return n, 0 + + d = 2 + m = trailing(n) + if m: + factors[d] = m + n >>= m + d = 3 + if limit < d: + if n > 1: + factors[n] = 1 + return done(n, d) + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + + # when d*d exceeds maxx or n we are done; if limit**2 is greater + # than n then maxx is set to zero so the value of n will flag the finish + if limit*limit > n: + maxx = 0 + else: + maxx = limit*limit + + dd = maxx or n + d = 5 + fails = 0 + while fails < fail_max: + if d*d > dd: + break + # d = 6*i - 1 + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + dd = maxx or n + fails = 0 + else: + fails += 1 + d += 2 + if d*d > dd: + break + # d = 6*i - 1 + # reduce + m = 0 + while n % d == 0: + n //= d + m += 1 + if m == 20: + mm = multiplicity(d, n) + m += mm + n //= d**mm + break + if m: + factors[d] = m + dd = maxx or n + fails = 0 + else: + fails += 1 + # d = 6*(i + 1) - 1 + d += 4 + + return done(n, d) + + +def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, + use_ecm=True, verbose=False, visual=None, multiple=False): + r""" + Given a positive integer ``n``, ``factorint(n)`` returns a dict containing + the prime factors of ``n`` as keys and their respective multiplicities + as values. For example: + + >>> from sympy.ntheory import factorint + >>> factorint(2000) # 2000 = (2**4) * (5**3) + {2: 4, 5: 3} + >>> factorint(65537) # This number is prime + {65537: 1} + + For input less than 2, factorint behaves as follows: + + - ``factorint(1)`` returns the empty factorization, ``{}`` + - ``factorint(0)`` returns ``{0:1}`` + - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n`` + + Partial Factorization: + + If ``limit`` (> 3) is specified, the search is stopped after performing + trial division up to (and including) the limit (or taking a + corresponding number of rho/p-1 steps). This is useful if one has + a large number and only is interested in finding small factors (if + any). Note that setting a limit does not prevent larger factors + from being found early; it simply means that the largest factor may + be composite. Since checking for perfect power is relatively cheap, it is + done regardless of the limit setting. + + This number, for example, has two small factors and a huge + semi-prime factor that cannot be reduced easily: + + >>> from sympy.ntheory import isprime + >>> a = 1407633717262338957430697921446883 + >>> f = factorint(a, limit=10000) + >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1} + True + >>> isprime(max(f)) + False + + This number has a small factor and a residual perfect power whose + base is greater than the limit: + + >>> factorint(3*101**7, limit=5) + {3: 1, 101: 7} + + List of Factors: + + If ``multiple`` is set to ``True`` then a list containing the + prime factors including multiplicities is returned. + + >>> factorint(24, multiple=True) + [2, 2, 2, 3] + + Visual Factorization: + + If ``visual`` is set to ``True``, then it will return a visual + factorization of the integer. For example: + + >>> from sympy import pprint + >>> pprint(factorint(4200, visual=True)) + 3 1 2 1 + 2 *3 *5 *7 + + Note that this is achieved by using the evaluate=False flag in Mul + and Pow. If you do other manipulations with an expression where + evaluate=False, it may evaluate. Therefore, you should use the + visual option only for visualization, and use the normal dictionary + returned by visual=False if you want to perform operations on the + factors. + + You can easily switch between the two forms by sending them back to + factorint: + + >>> from sympy import Mul + >>> regular = factorint(1764); regular + {2: 2, 3: 2, 7: 2} + >>> pprint(factorint(regular)) + 2 2 2 + 2 *3 *7 + + >>> visual = factorint(1764, visual=True); pprint(visual) + 2 2 2 + 2 *3 *7 + >>> print(factorint(visual)) + {2: 2, 3: 2, 7: 2} + + If you want to send a number to be factored in a partially factored form + you can do so with a dictionary or unevaluated expression: + + >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form + {2: 10, 3: 3} + >>> factorint(Mul(4, 12, evaluate=False)) + {2: 4, 3: 1} + + The table of the output logic is: + + ====== ====== ======= ======= + Visual + ------ ---------------------- + Input True False other + ====== ====== ======= ======= + dict mul dict mul + n mul dict dict + mul mul dict dict + ====== ====== ======= ======= + + Notes + ===== + + Algorithm: + + The function switches between multiple algorithms. Trial division + quickly finds small factors (of the order 1-5 digits), and finds + all large factors if given enough time. The Pollard rho and p-1 + algorithms are used to find large factors ahead of time; they + will often find factors of the order of 10 digits within a few + seconds: + + >>> factors = factorint(12345678910111213141516) + >>> for base, exp in sorted(factors.items()): + ... print('%s %s' % (base, exp)) + ... + 2 2 + 2507191691 1 + 1231026625769 1 + + Any of these methods can optionally be disabled with the following + boolean parameters: + + - ``use_trial``: Toggle use of trial division + - ``use_rho``: Toggle use of Pollard's rho method + - ``use_pm1``: Toggle use of Pollard's p-1 method + + ``factorint`` also periodically checks if the remaining part is + a prime number or a perfect power, and in those cases stops. + + For unevaluated factorial, it uses Legendre's formula(theorem). + + + If ``verbose`` is set to ``True``, detailed progress is printed. + + See Also + ======== + + smoothness, smoothness_p, divisors + + """ + if isinstance(n, Dict): + n = dict(n) + if multiple: + fac = factorint(n, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False, multiple=False) + factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) + for p in sorted(fac)), []) + return factorlist + + factordict = {} + if visual and not isinstance(n, (Mul, dict)): + factordict = factorint(n, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False) + elif isinstance(n, Mul): + factordict = {int(k): int(v) for k, v in + n.as_powers_dict().items()} + elif isinstance(n, dict): + factordict = n + if factordict and isinstance(n, (Mul, dict)): + # check it + for key in list(factordict.keys()): + if isprime(key): + continue + e = factordict.pop(key) + d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho, + use_pm1=use_pm1, verbose=verbose, visual=False) + for k, v in d.items(): + if k in factordict: + factordict[k] += v*e + else: + factordict[k] = v*e + if visual or (type(n) is dict and + visual is not True and + visual is not False): + if factordict == {}: + return S.One + if -1 in factordict: + factordict.pop(-1) + args = [S.NegativeOne] + else: + args = [] + args.extend([Pow(*i, evaluate=False) + for i in sorted(factordict.items())]) + return Mul(*args, evaluate=False) + elif isinstance(n, (dict, Mul)): + return factordict + + assert use_trial or use_rho or use_pm1 or use_ecm + + from sympy.functions.combinatorial.factorials import factorial + if isinstance(n, factorial): + x = as_int(n.args[0]) + if x >= 20: + factors = {} + m = 2 # to initialize the if condition below + for p in sieve.primerange(2, x + 1): + if m > 1: + m, q = 0, x // p + while q != 0: + m += q + q //= p + factors[p] = m + if factors and verbose: + for k in sorted(factors): + print(factor_msg % (k, factors[k])) + if verbose: + print(complete_msg) + return factors + else: + # if n < 20!, direct computation is faster + # since it uses a lookup table + n = n.func(x) + + n = as_int(n) + if limit: + limit = int(limit) + use_ecm = False + + # special cases + if n < 0: + factors = factorint( + -n, limit=limit, use_trial=use_trial, use_rho=use_rho, + use_pm1=use_pm1, verbose=verbose, visual=False) + factors[-1] = 1 + return factors + + if limit and limit < 2: + if n == 1: + return {} + return {n: 1} + elif n < 10: + # doing this we are assured of getting a limit > 2 + # when we have to compute it later + return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1}, + {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n] + + factors = {} + + # do simplistic factorization + if verbose: + sn = str(n) + if len(sn) > 50: + print('Factoring %s' % sn[:5] + \ + '..(%i other digits)..' % (len(sn) - 10) + sn[-5:]) + else: + print('Factoring', n) + + if use_trial: + # this is the preliminary factorization for small factors + small = 2**15 + fail_max = 600 + small = min(small, limit or small) + if verbose: + print(trial_int_msg % (2, small, fail_max)) + n, next_p = _factorint_small(factors, n, small, fail_max) + else: + next_p = 2 + if factors and verbose: + for k in sorted(factors): + print(factor_msg % (k, factors[k])) + if next_p == 0: + if n > 1: + factors[int(n)] = 1 + if verbose: + print(complete_msg) + return factors + + # continue with more advanced factorization methods + + # first check if the simplistic run didn't finish + # because of the limit and check for a perfect + # power before exiting + try: + if limit and next_p > limit: + if verbose: + print('Exceeded limit:', limit) + + _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, + verbose) + + if n > 1: + factors[int(n)] = 1 + return factors + else: + # Before quitting (or continuing on)... + + # ...do a Fermat test since it's so easy and we need the + # square root anyway. Finding 2 factors is easy if they are + # "close enough." This is the big root equivalent of dividing by + # 2, 3, 5. + sqrt_n = integer_nthroot(n, 2)[0] + a = sqrt_n + 1 + a2 = a**2 + b2 = a2 - n + for i in range(3): + b, fermat = integer_nthroot(b2, 2) + if fermat: + break + b2 += 2*a + 1 # equiv to (a + 1)**2 - n + a += 1 + if fermat: + if verbose: + print(fermat_msg) + if limit: + limit -= 1 + for r in [a - b, a + b]: + facs = factorint(r, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose) + for k, v in facs.items(): + factors[k] = factors.get(k, 0) + v + raise StopIteration + + # ...see if factorization can be terminated + _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, + verbose) + + except StopIteration: + if verbose: + print(complete_msg) + return factors + + # these are the limits for trial division which will + # be attempted in parallel with pollard methods + low, high = next_p, 2*next_p + + limit = limit or sqrt_n + # add 1 to make sure limit is reached in primerange calls + limit += 1 + iteration = 0 + while 1: + + try: + high_ = high + if limit < high_: + high_ = limit + + # Trial division + if use_trial: + if verbose: + print(trial_msg % (low, high_)) + ps = sieve.primerange(low, high_) + n, found_trial = _trial(factors, n, ps, verbose) + if found_trial: + _check_termination(factors, n, limit, use_trial, use_rho, + use_pm1, verbose) + else: + found_trial = False + + if high > limit: + if verbose: + print('Exceeded limit:', limit) + if n > 1: + factors[int(n)] = 1 + raise StopIteration + + # Only used advanced methods when no small factors were found + if not found_trial: + if (use_pm1 or use_rho): + high_root = max(int(math.log(high_**0.7)), low, 3) + + # Pollard p-1 + if use_pm1: + if verbose: + print(pm1_msg % (high_root, high_)) + c = pollard_pm1(n, B=high_root, seed=high_) + if c: + # factor it and let _trial do the update + ps = factorint(c, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + + # Pollard rho + if use_rho: + max_steps = high_root + if verbose: + print(rho_msg % (1, max_steps, high_)) + c = pollard_rho(n, retries=1, max_steps=max_steps, + seed=high_) + if c: + # factor it and let _trial do the update + ps = factorint(c, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + + except StopIteration: + if verbose: + print(complete_msg) + return factors + #Use subexponential algorithms if use_ecm + #Use pollard algorithms for finding small factors for 3 iterations + #if after small factors the number of digits of n is >= 20 then use ecm + iteration += 1 + if use_ecm and iteration >= 3 and len(str(n)) >= 25: + break + low, high = high, high*2 + B1 = 10000 + B2 = 100*B1 + num_curves = 50 + while(1): + if verbose: + print(ecm_msg % (B1, B2, num_curves)) + while(1): + try: + factor = _ecm_one_factor(n, B1, B2, num_curves) + ps = factorint(factor, limit=limit - 1, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + use_ecm=use_ecm, + verbose=verbose) + n, _ = _trial(factors, n, ps, verbose=False) + _check_termination(factors, n, limit, use_trial, + use_rho, use_pm1, verbose) + except ValueError: + break + except StopIteration: + if verbose: + print(complete_msg) + return factors + B1 *= 5 + B2 = 100*B1 + num_curves *= 4 + + +def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True, + verbose=False, visual=None, multiple=False): + r""" + Given a Rational ``r``, ``factorrat(r)`` returns a dict containing + the prime factors of ``r`` as keys and their respective multiplicities + as values. For example: + + >>> from sympy import factorrat, S + >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2) + {2: 3, 3: -2} + >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1) + {-1: 1, 3: -1, 7: -1, 47: -1} + + Please see the docstring for ``factorint`` for detailed explanations + and examples of the following keywords: + + - ``limit``: Integer limit up to which trial division is done + - ``use_trial``: Toggle use of trial division + - ``use_rho``: Toggle use of Pollard's rho method + - ``use_pm1``: Toggle use of Pollard's p-1 method + - ``verbose``: Toggle detailed printing of progress + - ``multiple``: Toggle returning a list of factors or dict + - ``visual``: Toggle product form of output + """ + if multiple: + fac = factorrat(rat, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose, visual=False, multiple=False) + factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) + for p, _ in sorted(fac.items(), + key=lambda elem: elem[0] + if elem[1] > 0 + else 1/elem[0])), []) + return factorlist + + f = factorint(rat.p, limit=limit, use_trial=use_trial, + use_rho=use_rho, use_pm1=use_pm1, + verbose=verbose).copy() + f = defaultdict(int, f) + for p, e in factorint(rat.q, limit=limit, + use_trial=use_trial, + use_rho=use_rho, + use_pm1=use_pm1, + verbose=verbose).items(): + f[p] += -e + + if len(f) > 1 and 1 in f: + del f[1] + if not visual: + return dict(f) + else: + if -1 in f: + f.pop(-1) + args = [S.NegativeOne] + else: + args = [] + args.extend([Pow(*i, evaluate=False) + for i in sorted(f.items())]) + return Mul(*args, evaluate=False) + + + +def primefactors(n, limit=None, verbose=False): + """Return a sorted list of n's prime factors, ignoring multiplicity + and any composite factor that remains if the limit was set too low + for complete factorization. Unlike factorint(), primefactors() does + not return -1 or 0. + + Examples + ======== + + >>> from sympy.ntheory import primefactors, factorint, isprime + >>> primefactors(6) + [2, 3] + >>> primefactors(-5) + [5] + + >>> sorted(factorint(123456).items()) + [(2, 6), (3, 1), (643, 1)] + >>> primefactors(123456) + [2, 3, 643] + + >>> sorted(factorint(10000000001, limit=200).items()) + [(101, 1), (99009901, 1)] + >>> isprime(99009901) + False + >>> primefactors(10000000001, limit=300) + [101] + + See Also + ======== + + divisors + """ + n = int(n) + factors = sorted(factorint(n, limit=limit, verbose=verbose).keys()) + s = [f for f in factors[:-1:] if f not in [-1, 0, 1]] + if factors and isprime(factors[-1]): + s += [factors[-1]] + return s + + +def _divisors(n, proper=False): + """Helper function for divisors which generates the divisors.""" + + factordict = factorint(n) + ps = sorted(factordict.keys()) + + def rec_gen(n=0): + if n == len(ps): + yield 1 + else: + pows = [1] + for j in range(factordict[ps[n]]): + pows.append(pows[-1] * ps[n]) + for q in rec_gen(n + 1): + for p in pows: + yield p * q + + if proper: + for p in rec_gen(): + if p != n: + yield p + else: + yield from rec_gen() + + +def divisors(n, generator=False, proper=False): + r""" + Return all divisors of n sorted from 1..n by default. + If generator is ``True`` an unordered generator is returned. + + The number of divisors of n can be quite large if there are many + prime factors (counting repeated factors). If only the number of + factors is desired use divisor_count(n). + + Examples + ======== + + >>> from sympy import divisors, divisor_count + >>> divisors(24) + [1, 2, 3, 4, 6, 8, 12, 24] + >>> divisor_count(24) + 8 + + >>> list(divisors(120, generator=True)) + [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] + + Notes + ===== + + This is a slightly modified version of Tim Peters referenced at: + https://stackoverflow.com/questions/1010381/python-factorization + + See Also + ======== + + primefactors, factorint, divisor_count + """ + + n = as_int(abs(n)) + if isprime(n): + if proper: + return [1] + return [1, n] + if n == 1: + if proper: + return [] + return [1] + if n == 0: + return [] + rv = _divisors(n, proper) + if not generator: + return sorted(rv) + return rv + + +def divisor_count(n, modulus=1, proper=False): + """ + Return the number of divisors of ``n``. If ``modulus`` is not 1 then only + those that are divisible by ``modulus`` are counted. If ``proper`` is True + then the divisor of ``n`` will not be counted. + + Examples + ======== + + >>> from sympy import divisor_count + >>> divisor_count(6) + 4 + >>> divisor_count(6, 2) + 2 + >>> divisor_count(6, proper=True) + 3 + + See Also + ======== + + factorint, divisors, totient, proper_divisor_count + + """ + + if not modulus: + return 0 + elif modulus != 1: + n, r = divmod(n, modulus) + if r: + return 0 + if n == 0: + return 0 + n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1]) + if n and proper: + n -= 1 + return n + + +def proper_divisors(n, generator=False): + """ + Return all divisors of n except n, sorted by default. + If generator is ``True`` an unordered generator is returned. + + Examples + ======== + + >>> from sympy import proper_divisors, proper_divisor_count + >>> proper_divisors(24) + [1, 2, 3, 4, 6, 8, 12] + >>> proper_divisor_count(24) + 7 + >>> list(proper_divisors(120, generator=True)) + [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60] + + See Also + ======== + + factorint, divisors, proper_divisor_count + + """ + return divisors(n, generator=generator, proper=True) + + +def proper_divisor_count(n, modulus=1): + """ + Return the number of proper divisors of ``n``. + + Examples + ======== + + >>> from sympy import proper_divisor_count + >>> proper_divisor_count(6) + 3 + >>> proper_divisor_count(6, modulus=2) + 1 + + See Also + ======== + + divisors, proper_divisors, divisor_count + + """ + return divisor_count(n, modulus=modulus, proper=True) + + +def _udivisors(n): + """Helper function for udivisors which generates the unitary divisors.""" + + factorpows = [p**e for p, e in factorint(n).items()] + for i in range(2**len(factorpows)): + d, j, k = 1, i, 0 + while j: + if (j & 1): + d *= factorpows[k] + j >>= 1 + k += 1 + yield d + + +def udivisors(n, generator=False): + r""" + Return all unitary divisors of n sorted from 1..n by default. + If generator is ``True`` an unordered generator is returned. + + The number of unitary divisors of n can be quite large if there are many + prime factors. If only the number of unitary divisors is desired use + udivisor_count(n). + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisors, udivisor_count + >>> udivisors(15) + [1, 3, 5, 15] + >>> udivisor_count(15) + 4 + + >>> sorted(udivisors(120, generator=True)) + [1, 3, 5, 8, 15, 24, 40, 120] + + See Also + ======== + + primefactors, factorint, divisors, divisor_count, udivisor_count + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Unitary_divisor + .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html + + """ + + n = as_int(abs(n)) + if isprime(n): + return [1, n] + if n == 1: + return [1] + if n == 0: + return [] + rv = _udivisors(n) + if not generator: + return sorted(rv) + return rv + + +def udivisor_count(n): + """ + Return the number of unitary divisors of ``n``. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisor_count + >>> udivisor_count(120) + 8 + + See Also + ======== + + factorint, divisors, udivisors, divisor_count, totient + + References + ========== + + .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html + + """ + + if n == 0: + return 0 + return 2**len([p for p in factorint(n) if p > 1]) + + +def _antidivisors(n): + """Helper function for antidivisors which generates the antidivisors.""" + + for d in _divisors(n): + y = 2*d + if n > y and n % y: + yield y + for d in _divisors(2*n-1): + if n > d >= 2 and n % d: + yield d + for d in _divisors(2*n+1): + if n > d >= 2 and n % d: + yield d + + +def antidivisors(n, generator=False): + r""" + Return all antidivisors of n sorted from 1..n by default. + + Antidivisors [1]_ of n are numbers that do not divide n by the largest + possible margin. If generator is True an unordered generator is returned. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import antidivisors + >>> antidivisors(24) + [7, 16] + + >>> sorted(antidivisors(128, generator=True)) + [3, 5, 15, 17, 51, 85] + + See Also + ======== + + primefactors, factorint, divisors, divisor_count, antidivisor_count + + References + ========== + + .. [1] definition is described in https://oeis.org/A066272/a066272a.html + + """ + + n = as_int(abs(n)) + if n <= 2: + return [] + rv = _antidivisors(n) + if not generator: + return sorted(rv) + return rv + + +def antidivisor_count(n): + """ + Return the number of antidivisors [1]_ of ``n``. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory.factor_ import antidivisor_count + >>> antidivisor_count(13) + 4 + >>> antidivisor_count(27) + 5 + + See Also + ======== + + factorint, divisors, antidivisors, divisor_count, totient + + References + ========== + + .. [1] formula from https://oeis.org/A066272 + + """ + + n = as_int(abs(n)) + if n <= 2: + return 0 + return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \ + divisor_count(n) - divisor_count(n, 2) - 5 + + +class totient(Function): + r""" + Calculate the Euler totient function phi(n) + + ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n + that are relatively prime to n. + + Parameters + ========== + + n : integer + + Examples + ======== + + >>> from sympy.ntheory import totient + >>> totient(1) + 1 + >>> totient(25) + 20 + >>> totient(45) == totient(5)*totient(9) + True + + See Also + ======== + + divisor_count + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function + .. [2] https://mathworld.wolfram.com/TotientFunction.html + + """ + @classmethod + def eval(cls, n): + if n.is_Integer: + if n < 1: + raise ValueError("n must be a positive integer") + factors = factorint(n) + return cls._from_factors(factors) + elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False): + raise ValueError("n must be a positive integer") + + def _eval_is_integer(self): + return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) + + @classmethod + def _from_distinct_primes(self, *args): + """Subroutine to compute totient from the list of assumed + distinct primes + + Examples + ======== + + >>> from sympy.ntheory.factor_ import totient + >>> totient._from_distinct_primes(5, 7) + 24 + """ + return reduce(lambda i, j: i * (j-1), args, 1) + + @classmethod + def _from_factors(self, factors): + """Subroutine to compute totient from already-computed factors + + Examples + ======== + + >>> from sympy.ntheory.factor_ import totient + >>> totient._from_factors({5: 2}) + 20 + """ + t = 1 + for p, k in factors.items(): + t *= (p - 1) * p**(k - 1) + return t + + +class reduced_totient(Function): + r""" + Calculate the Carmichael reduced totient function lambda(n) + + ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that + `k^m \equiv 1 \mod n` for all k relatively prime to n. + + Examples + ======== + + >>> from sympy.ntheory import reduced_totient + >>> reduced_totient(1) + 1 + >>> reduced_totient(8) + 2 + >>> reduced_totient(30) + 4 + + See Also + ======== + + totient + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Carmichael_function + .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html + + """ + @classmethod + def eval(cls, n): + if n.is_Integer: + if n < 1: + raise ValueError("n must be a positive integer") + factors = factorint(n) + return cls._from_factors(factors) + + @classmethod + def _from_factors(self, factors): + """Subroutine to compute totient from already-computed factors + """ + t = 1 + for p, k in factors.items(): + if p == 2 and k > 2: + t = ilcm(t, 2**(k - 2)) + else: + t = ilcm(t, (p - 1) * p**(k - 1)) + return t + + @classmethod + def _from_distinct_primes(self, *args): + """Subroutine to compute totient from the list of assumed + distinct primes + """ + args = [p - 1 for p in args] + return ilcm(*args) + + def _eval_is_integer(self): + return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) + + +class divisor_sigma(Function): + r""" + Calculate the divisor function `\sigma_k(n)` for positive integer n + + ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])`` + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots + + p_i^{m_ik}). + + Parameters + ========== + + n : integer + + k : integer, optional + power of divisors in the sum + + for k = 0, 1: + ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)`` + ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))`` + + Default for k is 1. + + Examples + ======== + + >>> from sympy.ntheory import divisor_sigma + >>> divisor_sigma(18, 0) + 6 + >>> divisor_sigma(39, 1) + 56 + >>> divisor_sigma(12, 2) + 210 + >>> divisor_sigma(37) + 38 + + See Also + ======== + + divisor_count, totient, divisors, factorint + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Divisor_function + + """ + + @classmethod + def eval(cls, n, k=S.One): + k = sympify(k) + + if n.is_prime: + return 1 + n**k + + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + elif k.is_Integer: + k = int(k) + return Integer(math.prod( + (p**(k*(e + 1)) - 1)//(p**k - 1) if k != 0 + else e + 1 for p, e in factorint(n).items())) + else: + return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0 + else e + 1 for p, e in factorint(n).items()]) + + if n.is_integer: # symbolic case + args = [] + for p, e in (_.as_base_exp() for _ in Mul.make_args(n)): + if p.is_prime and e.is_positive: + args.append((p**(k*(e + 1)) - 1)/(p**k - 1) if + k != 0 else e + 1) + else: + return + return Mul(*args) + + +def core(n, t=2): + r""" + Calculate core(n, t) = `core_t(n)` of a positive integer n + + ``core_2(n)`` is equal to the squarefree part of n + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}. + + Parameters + ========== + + n : integer + + t : integer + core(n, t) calculates the t-th power free part of n + + ``core(n, 2)`` is the squarefree part of ``n`` + ``core(n, 3)`` is the cubefree part of ``n`` + + Default for t is 2. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import core + >>> core(24, 2) + 6 + >>> core(9424, 3) + 1178 + >>> core(379238) + 379238 + >>> core(15**11, 10) + 15 + + See Also + ======== + + factorint, sympy.solvers.diophantine.diophantine.square_factor + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core + + """ + + n = as_int(n) + t = as_int(t) + if n <= 0: + raise ValueError("n must be a positive integer") + elif t <= 1: + raise ValueError("t must be >= 2") + else: + y = 1 + for p, e in factorint(n).items(): + y *= p**(e % t) + return y + + +class udivisor_sigma(Function): + r""" + Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n + + ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])`` + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^\omega p_i^{m_i}, + + then + + .. math :: + \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}). + + Parameters + ========== + + k : power of divisors in the sum + + for k = 0, 1: + ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)`` + ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))`` + + Default for k is 1. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import udivisor_sigma + >>> udivisor_sigma(18, 0) + 4 + >>> udivisor_sigma(74, 1) + 114 + >>> udivisor_sigma(36, 3) + 47450 + >>> udivisor_sigma(111) + 152 + + See Also + ======== + + divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma, + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html + + """ + + @classmethod + def eval(cls, n, k=S.One): + k = sympify(k) + if n.is_prime: + return 1 + n**k + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return Mul(*[1+p**(k*e) for p, e in factorint(n).items()]) + + +class primenu(Function): + r""" + Calculate the number of distinct prime factors for a positive integer n. + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^k p_i^{m_i}, + + then ``primenu(n)`` or `\nu(n)` is: + + .. math :: + \nu(n) = k. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import primenu + >>> primenu(1) + 0 + >>> primenu(30) + 3 + + See Also + ======== + + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/PrimeFactor.html + + """ + + @classmethod + def eval(cls, n): + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return len(factorint(n).keys()) + + +class primeomega(Function): + r""" + Calculate the number of prime factors counting multiplicities for a + positive integer n. + + If n's prime factorization is: + + .. math :: + n = \prod_{i=1}^k p_i^{m_i}, + + then ``primeomega(n)`` or `\Omega(n)` is: + + .. math :: + \Omega(n) = \sum_{i=1}^k m_i. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import primeomega + >>> primeomega(1) + 0 + >>> primeomega(20) + 3 + + See Also + ======== + + factorint + + References + ========== + + .. [1] https://mathworld.wolfram.com/PrimeFactor.html + + """ + + @classmethod + def eval(cls, n): + if n.is_Integer: + if n <= 0: + raise ValueError("n must be a positive integer") + else: + return sum(factorint(n).values()) + + +def mersenne_prime_exponent(nth): + """Returns the exponent ``i`` for the nth Mersenne prime (which + has the form `2^i - 1`). + + Examples + ======== + + >>> from sympy.ntheory.factor_ import mersenne_prime_exponent + >>> mersenne_prime_exponent(1) + 2 + >>> mersenne_prime_exponent(20) + 4423 + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2") + if n > 51: + raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51") + return MERSENNE_PRIME_EXPONENTS[n - 1] + + +def is_perfect(n): + """Returns True if ``n`` is a perfect number, else False. + + A perfect number is equal to the sum of its positive, proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_perfect, divisors, divisor_sigma + >>> is_perfect(20) + False + >>> is_perfect(6) + True + >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1]) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/PerfectNumber.html + .. [2] https://en.wikipedia.org/wiki/Perfect_number + + """ + + n = as_int(n) + if _isperfect(n): + return True + + # all perfect numbers for Mersenne primes with exponents + # less than or equal to 43112609 are known + iknow = MERSENNE_PRIME_EXPONENTS.index(43112609) + if iknow <= len(PERFECT) - 1 and n <= PERFECT[iknow]: + # there may be gaps between this and larger known values + # so only conclude in the range for which all values + # are known + return False + if n%2 == 0: + last2 = n % 100 + if last2 != 28 and last2 % 10 != 6: + return False + r, b = integer_nthroot(1 + 8*n, 2) + if not b: + return False + m, x = divmod(1 + r, 4) + if x: + return False + e, b = integer_log(m, 2) + if not b: + return False + else: + if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/ + return False + if n % 105 == 0: # not divis by 105 + return False + if not any(n%m == r for m, r in [(12, 1), (468, 117), (324, 81)]): + return False + # there are many criteria that the factor structure of n + # must meet; since we will have to factor it to test the + # structure we will have the factors and can then check + # to see whether it is a perfect number or not. So we + # skip the structure checks and go straight to the final + # test below. + rv = divisor_sigma(n) - n + if rv == n: + if n%2 == 0: + raise ValueError(filldedent(''' + This even number is perfect and is associated with a + Mersenne Prime, 2^%s - 1. It should be + added to SymPy.''' % (e + 1))) + else: + raise ValueError(filldedent('''In 1888, Sylvester stated: " + ...a prolonged meditation on the subject has satisfied + me that the existence of any one such [odd perfect number] + -- its escape, so to say, from the complex web of conditions + which hem it in on all sides -- would be little short of a + miracle." I guess SymPy just found that miracle and it + factors like this: %s''' % factorint(n))) + + +def is_mersenne_prime(n): + """Returns True if ``n`` is a Mersenne prime, else False. + + A Mersenne prime is a prime number having the form `2^i - 1`. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_mersenne_prime + >>> is_mersenne_prime(6) + False + >>> is_mersenne_prime(127) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/MersennePrime.html + + """ + + n = as_int(n) + if _ismersenneprime(n): + return True + if not isprime(n): + return False + r, b = integer_log(n + 1, 2) + if not b: + return False + raise ValueError(filldedent(''' + This Mersenne Prime, 2^%s - 1, should + be added to SymPy's known values.''' % r)) + + +def abundance(n): + """Returns the difference between the sum of the positive + proper divisors of a number and the number. + + Examples + ======== + + >>> from sympy.ntheory import abundance, is_perfect, is_abundant + >>> abundance(6) + 0 + >>> is_perfect(6) + True + >>> abundance(10) + -2 + >>> is_abundant(10) + False + """ + return divisor_sigma(n, 1) - 2 * n + + +def is_abundant(n): + """Returns True if ``n`` is an abundant number, else False. + + A abundant number is smaller than the sum of its positive proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_abundant + >>> is_abundant(20) + True + >>> is_abundant(15) + False + + References + ========== + + .. [1] https://mathworld.wolfram.com/AbundantNumber.html + + """ + n = as_int(n) + if is_perfect(n): + return False + return n % 6 == 0 or bool(abundance(n) > 0) + + +def is_deficient(n): + """Returns True if ``n`` is a deficient number, else False. + + A deficient number is greater than the sum of its positive proper divisors. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_deficient + >>> is_deficient(20) + False + >>> is_deficient(15) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/DeficientNumber.html + + """ + n = as_int(n) + if is_perfect(n): + return False + return bool(abundance(n) < 0) + + +def is_amicable(m, n): + """Returns True if the numbers `m` and `n` are "amicable", else False. + + Amicable numbers are two different numbers so related that the sum + of the proper divisors of each is equal to that of the other. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import is_amicable, divisor_sigma + >>> is_amicable(220, 284) + True + >>> divisor_sigma(220) == divisor_sigma(284) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Amicable_numbers + + """ + if m == n: + return False + a, b = (divisor_sigma(i) for i in (m, n)) + return a == b == (m + n) + + +def dra(n, b): + """ + Returns the additive digital root of a natural number ``n`` in base ``b`` + which is a single digit value obtained by an iterative process of summing + digits, on each iteration using the result from the previous iteration to + compute a digit sum. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import dra + >>> dra(3110, 12) + 8 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Digital_root + + """ + + num = abs(as_int(n)) + b = as_int(b) + if b <= 1: + raise ValueError("Base should be an integer greater than 1") + + if num == 0: + return 0 + + return (1 + (num - 1) % (b - 1)) + + +def drm(n, b): + """ + Returns the multiplicative digital root of a natural number ``n`` in a given + base ``b`` which is a single digit value obtained by an iterative process of + multiplying digits, on each iteration using the result from the previous + iteration to compute the digit multiplication. + + Examples + ======== + + >>> from sympy.ntheory.factor_ import drm + >>> drm(9876, 10) + 0 + + >>> drm(49, 10) + 8 + + References + ========== + + .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html + + """ + + n = abs(as_int(n)) + b = as_int(b) + if b <= 1: + raise ValueError("Base should be an integer greater than 1") + while n > b: + mul = 1 + while n > 1: + n, r = divmod(n, b) + if r == 0: + return 0 + mul *= r + n = mul + return n diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/generate.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..3814427daf9a08aa87423207eb132a824bcb6cb9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/generate.py @@ -0,0 +1,1037 @@ +""" +Generating and counting primes. + +""" + +import random +from bisect import bisect +from itertools import count +# Using arrays for sieving instead of lists greatly reduces +# memory consumption +from array import array as _array + +from sympy.core.function import Function +from sympy.core.singleton import S +from .primetest import isprime +from sympy.utilities.misc import as_int + + +def _azeros(n): + return _array('l', [0]*n) + + +def _aset(*v): + return _array('l', v) + + +def _arange(a, b): + return _array('l', range(a, b)) + + +def _as_int_ceiling(a): + """ Wrapping ceiling in as_int will raise an error if there was a problem + determining whether the expression was exactly an integer or not.""" + from sympy.functions.elementary.integers import ceiling + return as_int(ceiling(a)) + + +class Sieve: + """An infinite list of prime numbers, implemented as a dynamically + growing sieve of Eratosthenes. When a lookup is requested involving + an odd number that has not been sieved, the sieve is automatically + extended up to that number. + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> 25 in sieve + False + >>> sieve._list + array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) + """ + + # data shared (and updated) by all Sieve instances + def __init__(self): + self._n = 6 + self._list = _aset(2, 3, 5, 7, 11, 13) # primes + self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient + self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius + assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist)) + + def __repr__(self): + return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n" + "%s sieve (%i): %i, %i, %i, ... %i, %i\n" + "%s sieve (%i): %i, %i, %i, ... %i, %i>") % ( + 'prime', len(self._list), + self._list[0], self._list[1], self._list[2], + self._list[-2], self._list[-1], + 'totient', len(self._tlist), + self._tlist[0], self._tlist[1], + self._tlist[2], self._tlist[-2], self._tlist[-1], + 'mobius', len(self._mlist), + self._mlist[0], self._mlist[1], + self._mlist[2], self._mlist[-2], self._mlist[-1]) + + def _reset(self, prime=None, totient=None, mobius=None): + """Reset all caches (default). To reset one or more set the + desired keyword to True.""" + if all(i is None for i in (prime, totient, mobius)): + prime = totient = mobius = True + if prime: + self._list = self._list[:self._n] + if totient: + self._tlist = self._tlist[:self._n] + if mobius: + self._mlist = self._mlist[:self._n] + + def extend(self, n): + """Grow the sieve to cover all primes <= n (a real number). + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> sieve.extend(30) + >>> sieve[10] == 29 + True + """ + n = int(n) + if n <= self._list[-1]: + return + + # We need to sieve against all bases up to sqrt(n). + # This is a recursive call that will do nothing if there are enough + # known bases already. + maxbase = int(n**0.5) + 1 + self.extend(maxbase) + + # Create a new sieve starting from sqrt(n) + begin = self._list[-1] + 1 + newsieve = _arange(begin, n + 1) + + # Now eliminate all multiples of primes in [2, sqrt(n)] + for p in self.primerange(maxbase): + # Start counting at a multiple of p, offsetting + # the index to account for the new sieve's base index + startindex = (-begin) % p + for i in range(startindex, len(newsieve), p): + newsieve[i] = 0 + + # Merge the sieves + self._list += _array('l', [x for x in newsieve if x]) + + def extend_to_no(self, i): + """Extend to include the ith prime number. + + Parameters + ========== + + i : integer + + Examples + ======== + + >>> from sympy import sieve + >>> sieve._reset() # this line for doctest only + >>> sieve.extend_to_no(9) + >>> sieve._list + array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) + + Notes + ===== + + The list is extended by 50% if it is too short, so it is + likely that it will be longer than requested. + """ + i = as_int(i) + while len(self._list) < i: + self.extend(int(self._list[-1] * 1.5)) + + def primerange(self, a, b=None): + """Generate all prime numbers in the range [2, a) or [a, b). + + Examples + ======== + + >>> from sympy import sieve, prime + + All primes less than 19: + + >>> print([i for i in sieve.primerange(19)]) + [2, 3, 5, 7, 11, 13, 17] + + All primes greater than or equal to 7 and less than 19: + + >>> print([i for i in sieve.primerange(7, 19)]) + [7, 11, 13, 17] + + All primes through the 10th prime + + >>> list(sieve.primerange(prime(10) + 1)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + """ + + if b is None: + b = _as_int_ceiling(a) + a = 2 + else: + a = max(2, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + if a >= b: + return + self.extend(b) + i = self.search(a)[1] + maxi = len(self._list) + 1 + while i < maxi: + p = self._list[i - 1] + if p < b: + yield p + i += 1 + else: + return + + def totientrange(self, a, b): + """Generate all totient numbers for the range [a, b). + + Examples + ======== + + >>> from sympy import sieve + >>> print([i for i in sieve.totientrange(7, 18)]) + [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16] + """ + a = max(1, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + n = len(self._tlist) + if a >= b: + return + elif b <= n: + for i in range(a, b): + yield self._tlist[i] + else: + self._tlist += _arange(n, b) + for i in range(1, n): + ti = self._tlist[i] + startindex = (n + i - 1) // i * i + for j in range(startindex, b, i): + self._tlist[j] -= ti + if i >= a: + yield ti + + for i in range(n, b): + ti = self._tlist[i] + for j in range(2 * i, b, i): + self._tlist[j] -= ti + if i >= a: + yield ti + + def mobiusrange(self, a, b): + """Generate all mobius numbers for the range [a, b). + + Parameters + ========== + + a : integer + First number in range + + b : integer + First number outside of range + + Examples + ======== + + >>> from sympy import sieve + >>> print([i for i in sieve.mobiusrange(7, 18)]) + [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1] + """ + a = max(1, _as_int_ceiling(a)) + b = _as_int_ceiling(b) + n = len(self._mlist) + if a >= b: + return + elif b <= n: + for i in range(a, b): + yield self._mlist[i] + else: + self._mlist += _azeros(b - n) + for i in range(1, n): + mi = self._mlist[i] + startindex = (n + i - 1) // i * i + for j in range(startindex, b, i): + self._mlist[j] -= mi + if i >= a: + yield mi + + for i in range(n, b): + mi = self._mlist[i] + for j in range(2 * i, b, i): + self._mlist[j] -= mi + if i >= a: + yield mi + + def search(self, n): + """Return the indices i, j of the primes that bound n. + + If n is prime then i == j. + + Although n can be an expression, if ceiling cannot convert + it to an integer then an n error will be raised. + + Examples + ======== + + >>> from sympy import sieve + >>> sieve.search(25) + (9, 10) + >>> sieve.search(23) + (9, 9) + """ + test = _as_int_ceiling(n) + n = as_int(n) + if n < 2: + raise ValueError("n should be >= 2 but got: %s" % n) + if n > self._list[-1]: + self.extend(n) + b = bisect(self._list, n) + if self._list[b - 1] == test: + return b, b + else: + return b, b + 1 + + def __contains__(self, n): + try: + n = as_int(n) + assert n >= 2 + except (ValueError, AssertionError): + return False + if n % 2 == 0: + return n == 2 + a, b = self.search(n) + return a == b + + def __iter__(self): + for n in count(1): + yield self[n] + + def __getitem__(self, n): + """Return the nth prime number""" + if isinstance(n, slice): + self.extend_to_no(n.stop) + # Python 2.7 slices have 0 instead of None for start, so + # we can't default to 1. + start = n.start if n.start is not None else 0 + if start < 1: + # sieve[:5] would be empty (starting at -1), let's + # just be explicit and raise. + raise IndexError("Sieve indices start at 1.") + return self._list[start - 1:n.stop - 1:n.step] + else: + if n < 1: + # offset is one, so forbid explicit access to sieve[0] + # (would surprisingly return the last one). + raise IndexError("Sieve indices start at 1.") + n = as_int(n) + self.extend_to_no(n) + return self._list[n - 1] + +# Generate a global object for repeated use in trial division etc +sieve = Sieve() + + +def prime(nth): + r""" Return the nth prime, with the primes indexed as prime(1) = 2, + prime(2) = 3, etc.... The nth prime is approximately $n\log(n)$. + + Logarithmic integral of $x$ is a pretty nice approximation for number of + primes $\le x$, i.e. + li(x) ~ pi(x) + In fact, for the numbers we are concerned about( x<1e11 ), + li(x) - pi(x) < 50000 + + Also, + li(x) > pi(x) can be safely assumed for the numbers which + can be evaluated by this function. + + Here, we find the least integer m such that li(m) > n using binary search. + Now pi(m-1) < li(m-1) <= n, + + We find pi(m - 1) using primepi function. + + Starting from m, we have to find n - pi(m-1) more primes. + + For the inputs this implementation can handle, we will have to test + primality for at max about 10**5 numbers, to get our answer. + + Examples + ======== + + >>> from sympy import prime + >>> prime(10) + 29 + >>> prime(1) + 2 + >>> prime(100000) + 1299709 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + primepi : Return the number of primes less than or equal to n + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29 + .. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number + .. [3] https://en.wikipedia.org/wiki/Skewes%27_number + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; prime(1) == 2") + if n <= len(sieve._list): + return sieve[n] + + from sympy.functions.elementary.exponential import log + from sympy.functions.special.error_functions import li + a = 2 # Lower bound for binary search + b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. + + while a < b: + mid = (a + b) >> 1 + if li(mid) > n: + b = mid + else: + a = mid + 1 + n_primes = primepi(a - 1) + while n_primes < n: + if isprime(a): + n_primes += 1 + a += 1 + return a - 1 + + +class primepi(Function): + r""" Represents the prime counting function pi(n) = the number + of prime numbers less than or equal to n. + + Algorithm Description: + + In sieve method, we remove all multiples of prime p + except p itself. + + Let phi(i,j) be the number of integers 2 <= k <= i + which remain after sieving from primes less than + or equal to j. + Clearly, pi(n) = phi(n, sqrt(n)) + + If j is not a prime, + phi(i,j) = phi(i, j - 1) + + if j is a prime, + We remove all numbers(except j) whose + smallest prime factor is j. + + Let $x= j \times a$ be such a number, where $2 \le a \le i / j$ + Now, after sieving from primes $\le j - 1$, + a must remain + (because x, and hence a has no prime factor $\le j - 1$) + Clearly, there are phi(i / j, j - 1) such a + which remain on sieving from primes $\le j - 1$ + + Now, if a is a prime less than equal to j - 1, + $x= j \times a$ has smallest prime factor = a, and + has already been removed(by sieving from a). + So, we do not need to remove it again. + (Note: there will be pi(j - 1) such x) + + Thus, number of x, that will be removed are: + phi(i / j, j - 1) - phi(j - 1, j - 1) + (Note that pi(j - 1) = phi(j - 1, j - 1)) + + $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1) + + So,following recursion is used and implemented as dp: + + phi(a, b) = phi(a, b - 1), if b is not a prime + phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime + + Clearly a is always of the form floor(n / k), + which can take at most $2\sqrt{n}$ values. + Two arrays arr1,arr2 are maintained + arr1[i] = phi(i, j), + arr2[i] = phi(n // i, j) + + Finally the answer is arr2[1] + + Examples + ======== + + >>> from sympy import primepi, prime, prevprime, isprime + >>> primepi(25) + 9 + + So there are 9 primes less than or equal to 25. Is 25 prime? + + >>> isprime(25) + False + + It is not. So the first prime less than 25 must be the + 9th prime: + + >>> prevprime(25) == prime(9) + True + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + prime : Return the nth prime + """ + @classmethod + def eval(cls, n): + if n is S.Infinity: + return S.Infinity + if n is S.NegativeInfinity: + return S.Zero + + try: + n = int(n) + except TypeError: + if n.is_real == False or n is S.NaN: + raise ValueError("n must be real") + return + + if n < 2: + return S.Zero + if n <= sieve._list[-1]: + return S(sieve.search(n)[0]) + lim = int(n ** 0.5) + lim -= 1 + lim = max(lim, 0) + while lim * lim <= n: + lim += 1 + lim -= 1 + arr1 = [0] * (lim + 1) + arr2 = [0] * (lim + 1) + for i in range(1, lim + 1): + arr1[i] = i - 1 + arr2[i] = n // i - 1 + for i in range(2, lim + 1): + # Presently, arr1[k]=phi(k,i - 1), + # arr2[k] = phi(n // k,i - 1) + if arr1[i] == arr1[i - 1]: + continue + p = arr1[i - 1] + for j in range(1, min(n // (i * i), lim) + 1): + st = i * j + if st <= lim: + arr2[j] -= arr2[st] - p + else: + arr2[j] -= arr1[n // st] - p + lim2 = min(lim, i * i - 1) + for j in range(lim, lim2, -1): + arr1[j] -= arr1[j // i] - p + return S(arr2[1]) + + +def nextprime(n, ith=1): + """ Return the ith prime greater than n. + + i must be an integer. + + Notes + ===== + + Potential primes are located at 6*j +/- 1. This + property is used during searching. + + >>> from sympy import nextprime + >>> [(i, nextprime(i)) for i in range(10, 15)] + [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] + >>> nextprime(2, ith=2) # the 2nd prime after 2 + 5 + + See Also + ======== + + prevprime : Return the largest prime smaller than n + primerange : Generate all primes in a given range + + """ + n = int(n) + i = as_int(ith) + if i > 1: + pr = n + j = 1 + while 1: + pr = nextprime(pr) + j += 1 + if j > i: + break + return pr + + if n < 2: + return 2 + if n < 7: + return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] + if n <= sieve._list[-2]: + l, u = sieve.search(n) + if l == u: + return sieve[u + 1] + else: + return sieve[u] + nn = 6*(n//6) + if nn == n: + n += 1 + if isprime(n): + return n + n += 4 + elif n - nn == 5: + n += 2 + if isprime(n): + return n + n += 4 + else: + n = nn + 5 + while 1: + if isprime(n): + return n + n += 2 + if isprime(n): + return n + n += 4 + + +def prevprime(n): + """ Return the largest prime smaller than n. + + Notes + ===== + + Potential primes are located at 6*j +/- 1. This + property is used during searching. + + >>> from sympy import prevprime + >>> [(i, prevprime(i)) for i in range(10, 15)] + [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] + + See Also + ======== + + nextprime : Return the ith prime greater than n + primerange : Generates all primes in a given range + """ + n = _as_int_ceiling(n) + if n < 3: + raise ValueError("no preceding primes") + if n < 8: + return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] + if n <= sieve._list[-1]: + l, u = sieve.search(n) + if l == u: + return sieve[l-1] + else: + return sieve[l] + nn = 6*(n//6) + if n - nn <= 1: + n = nn - 1 + if isprime(n): + return n + n -= 4 + else: + n = nn + 1 + while 1: + if isprime(n): + return n + n -= 2 + if isprime(n): + return n + n -= 4 + + +def primerange(a, b=None): + """ Generate a list of all prime numbers in the range [2, a), + or [a, b). + + If the range exists in the default sieve, the values will + be returned from there; otherwise values will be returned + but will not modify the sieve. + + Examples + ======== + + >>> from sympy import primerange, prime + + All primes less than 19: + + >>> list(primerange(19)) + [2, 3, 5, 7, 11, 13, 17] + + All primes greater than or equal to 7 and less than 19: + + >>> list(primerange(7, 19)) + [7, 11, 13, 17] + + All primes through the 10th prime + + >>> list(primerange(prime(10) + 1)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + The Sieve method, primerange, is generally faster but it will + occupy more memory as the sieve stores values. The default + instance of Sieve, named sieve, can be used: + + >>> from sympy import sieve + >>> list(sieve.primerange(1, 30)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + Notes + ===== + + Some famous conjectures about the occurrence of primes in a given + range are [1]: + + - Twin primes: though often not, the following will give 2 primes + an infinite number of times: + primerange(6*n - 1, 6*n + 2) + - Legendre's: the following always yields at least one prime + primerange(n**2, (n+1)**2+1) + - Bertrand's (proven): there is always a prime in the range + primerange(n, 2*n) + - Brocard's: there are at least four primes in the range + primerange(prime(n)**2, prime(n+1)**2) + + The average gap between primes is log(n) [2]; the gap between + primes can be arbitrarily large since sequences of composite + numbers are arbitrarily large, e.g. the numbers in the sequence + n! + 2, n! + 3 ... n! + n are all composite. + + See Also + ======== + + prime : Return the nth prime + nextprime : Return the ith prime greater than n + prevprime : Return the largest prime smaller than n + randprime : Returns a random prime in a given range + primorial : Returns the product of primes based on condition + Sieve.primerange : return range from already computed primes + or extend the sieve to contain the requested + range. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Prime_number + .. [2] https://primes.utm.edu/notes/gaps.html + """ + if b is None: + a, b = 2, a + if a >= b: + return + # if we already have the range, return it + if b <= sieve._list[-1]: + yield from sieve.primerange(a, b) + return + # otherwise compute, without storing, the desired range. + + a = _as_int_ceiling(a) - 1 + b = _as_int_ceiling(b) + while 1: + a = nextprime(a) + if a < b: + yield a + else: + return + + +def randprime(a, b): + """ Return a random prime number in the range [a, b). + + Bertrand's postulate assures that + randprime(a, 2*a) will always succeed for a > 1. + + Examples + ======== + + >>> from sympy import randprime, isprime + >>> randprime(1, 30) #doctest: +SKIP + 13 + >>> isprime(randprime(1, 30)) + True + + See Also + ======== + + primerange : Generate all primes in a given range + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate + + """ + if a >= b: + return + a, b = map(int, (a, b)) + n = random.randint(a - 1, b) + p = nextprime(n) + if p >= b: + p = prevprime(b) + if p < a: + raise ValueError("no primes exist in the specified range") + return p + + +def primorial(n, nth=True): + """ + Returns the product of the first n primes (default) or + the primes less than or equal to n (when ``nth=False``). + + Examples + ======== + + >>> from sympy.ntheory.generate import primorial, primerange + >>> from sympy import factorint, Mul, primefactors, sqrt + >>> primorial(4) # the first 4 primes are 2, 3, 5, 7 + 210 + >>> primorial(4, nth=False) # primes <= 4 are 2 and 3 + 6 + >>> primorial(1) + 2 + >>> primorial(1, nth=False) + 1 + >>> primorial(sqrt(101), nth=False) + 210 + + One can argue that the primes are infinite since if you take + a set of primes and multiply them together (e.g. the primorial) and + then add or subtract 1, the result cannot be divided by any of the + original factors, hence either 1 or more new primes must divide this + product of primes. + + In this case, the number itself is a new prime: + + >>> factorint(primorial(4) + 1) + {211: 1} + + In this case two new primes are the factors: + + >>> factorint(primorial(4) - 1) + {11: 1, 19: 1} + + Here, some primes smaller and larger than the primes multiplied together + are obtained: + + >>> p = list(primerange(10, 20)) + >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p))) + [2, 5, 31, 149] + + See Also + ======== + + primerange : Generate all primes in a given range + + """ + if nth: + n = as_int(n) + else: + n = int(n) + if n < 1: + raise ValueError("primorial argument must be >= 1") + p = 1 + if nth: + for i in range(1, n + 1): + p *= prime(i) + else: + for i in primerange(2, n + 1): + p *= i + return p + + +def cycle_length(f, x0, nmax=None, values=False): + """For a given iterated sequence, return a generator that gives + the length of the iterated cycle (lambda) and the length of terms + before the cycle begins (mu); if ``values`` is True then the + terms of the sequence will be returned instead. The sequence is + started with value ``x0``. + + Note: more than the first lambda + mu terms may be returned and this + is the cost of cycle detection with Brent's method; there are, however, + generally less terms calculated than would have been calculated if the + proper ending point were determined, e.g. by using Floyd's method. + + >>> from sympy.ntheory.generate import cycle_length + + This will yield successive values of i <-- func(i): + + >>> def iter(func, i): + ... while 1: + ... ii = func(i) + ... yield ii + ... i = ii + ... + + A function is defined: + + >>> func = lambda i: (i**2 + 1) % 51 + + and given a seed of 4 and the mu and lambda terms calculated: + + >>> next(cycle_length(func, 4)) + (6, 2) + + We can see what is meant by looking at the output: + + >>> n = cycle_length(func, 4, values=True) + >>> list(ni for ni in n) + [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] + + There are 6 repeating values after the first 2. + + If a sequence is suspected of being longer than you might wish, ``nmax`` + can be used to exit early (and mu will be returned as None): + + >>> next(cycle_length(func, 4, nmax = 4)) + (4, None) + >>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)] + [17, 35, 2, 5] + + Code modified from: + https://en.wikipedia.org/wiki/Cycle_detection. + """ + + nmax = int(nmax or 0) + + # main phase: search successive powers of two + power = lam = 1 + tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0. + i = 0 + while tortoise != hare and (not nmax or i < nmax): + i += 1 + if power == lam: # time to start a new power of two? + tortoise = hare + power *= 2 + lam = 0 + if values: + yield hare + hare = f(hare) + lam += 1 + if nmax and i == nmax: + if values: + return + else: + yield nmax, None + return + if not values: + # Find the position of the first repetition of length lambda + mu = 0 + tortoise = hare = x0 + for i in range(lam): + hare = f(hare) + while tortoise != hare: + tortoise = f(tortoise) + hare = f(hare) + mu += 1 + if mu: + mu -= 1 + yield lam, mu + + +def composite(nth): + """ Return the nth composite number, with the composite numbers indexed as + composite(1) = 4, composite(2) = 6, etc.... + + Examples + ======== + + >>> from sympy import composite + >>> composite(36) + 52 + >>> composite(1) + 4 + >>> composite(17737) + 20000 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + primepi : Return the number of primes less than or equal to n + prime : Return the nth prime + compositepi : Return the number of positive composite numbers less than or equal to n + """ + n = as_int(nth) + if n < 1: + raise ValueError("nth must be a positive integer; composite(1) == 4") + composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18] + if n <= 10: + return composite_arr[n - 1] + + a, b = 4, sieve._list[-1] + if n <= b - primepi(b) - 1: + while a < b - 1: + mid = (a + b) >> 1 + if mid - primepi(mid) - 1 > n: + b = mid + else: + a = mid + if isprime(a): + a -= 1 + return a + + from sympy.functions.elementary.exponential import log + from sympy.functions.special.error_functions import li + a = 4 # Lower bound for binary search + b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. + + while a < b: + mid = (a + b) >> 1 + if mid - li(mid) - 1 > n: + b = mid + else: + a = mid + 1 + + n_composites = a - primepi(a) - 1 + while n_composites > n: + if not isprime(a): + n_composites -= 1 + a -= 1 + if isprime(a): + a -= 1 + return a + + +def compositepi(n): + """ Return the number of positive composite numbers less than or equal to n. + The first positive composite is 4, i.e. compositepi(4) = 1. + + Examples + ======== + + >>> from sympy import compositepi + >>> compositepi(25) + 15 + >>> compositepi(1000) + 831 + + See Also + ======== + + sympy.ntheory.primetest.isprime : Test if n is prime + primerange : Generate all primes in a given range + prime : Return the nth prime + primepi : Return the number of primes less than or equal to n + composite : Return the nth composite number + """ + n = int(n) + if n < 4: + return 0 + return n - primepi(n) - 1 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/modular.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/modular.py new file mode 100644 index 0000000000000000000000000000000000000000..2962f511ff1473978ca9fb624e202094474b00dd --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/modular.py @@ -0,0 +1,255 @@ +from functools import reduce +from math import prod + +from sympy.core.numbers import igcdex, igcd +from sympy.ntheory.primetest import isprime +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2 +from sympy.utilities.misc import as_int + + +def symmetric_residue(a, m): + """Return the residual mod m such that it is within half of the modulus. + + >>> from sympy.ntheory.modular import symmetric_residue + >>> symmetric_residue(1, 6) + 1 + >>> symmetric_residue(4, 6) + -2 + """ + if a <= m // 2: + return a + return a - m + + +def crt(m, v, symmetric=False, check=True): + r"""Chinese Remainder Theorem. + + The moduli in m are assumed to be pairwise coprime. The output + is then an integer f, such that f = v_i mod m_i for each pair out + of v and m. If ``symmetric`` is False a positive integer will be + returned, else \|f\| will be less than or equal to the LCM of the + moduli, and thus f may be negative. + + If the moduli are not co-prime the correct result will be returned + if/when the test of the result is found to be incorrect. This result + will be None if there is no solution. + + The keyword ``check`` can be set to False if it is known that the moduli + are coprime. + + Examples + ======== + + As an example consider a set of residues ``U = [49, 76, 65]`` + and a set of moduli ``M = [99, 97, 95]``. Then we have:: + + >>> from sympy.ntheory.modular import crt + + >>> crt([99, 97, 95], [49, 76, 65]) + (639985, 912285) + + This is the correct result because:: + + >>> [639985 % m for m in [99, 97, 95]] + [49, 76, 65] + + If the moduli are not co-prime, you may receive an incorrect result + if you use ``check=False``: + + >>> crt([12, 6, 17], [3, 4, 2], check=False) + (954, 1224) + >>> [954 % m for m in [12, 6, 17]] + [6, 0, 2] + >>> crt([12, 6, 17], [3, 4, 2]) is None + True + >>> crt([3, 6], [2, 5]) + (5, 6) + + Note: the order of gf_crt's arguments is reversed relative to crt, + and that solve_congruence takes residue, modulus pairs. + + Programmer's note: rather than checking that all pairs of moduli share + no GCD (an O(n**2) test) and rather than factoring all moduli and seeing + that there is no factor in common, a check that the result gives the + indicated residuals is performed -- an O(n) operation. + + See Also + ======== + + solve_congruence + sympy.polys.galoistools.gf_crt : low level crt routine used by this routine + """ + if check: + m = list(map(as_int, m)) + v = list(map(as_int, v)) + + result = gf_crt(v, m, ZZ) + mm = prod(m) + + if check: + if not all(v % m == result % m for v, m in zip(v, m)): + result = solve_congruence(*list(zip(v, m)), + check=False, symmetric=symmetric) + if result is None: + return result + result, mm = result + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def crt1(m): + """First part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1 + >>> crt1([18, 42, 6]) + (4536, [252, 108, 756], [0, 2, 0]) + """ + + return gf_crt1(m, ZZ) + + +def crt2(m, v, mm, e, s, symmetric=False): + """Second part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1, crt2 + >>> mm, e, s = crt1([18, 42, 6]) + >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s) + (0, 4536) + """ + + result = gf_crt2(v, m, mm, e, s, ZZ) + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def solve_congruence(*remainder_modulus_pairs, **hint): + """Compute the integer ``n`` that has the residual ``ai`` when it is + divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to + this function: ((a1, m1), (a2, m2), ...). If there is no solution, + return None. Otherwise return ``n`` and its modulus. + + The ``mi`` values need not be co-prime. If it is known that the moduli are + not co-prime then the hint ``check`` can be set to False (default=True) and + the check for a quicker solution via crt() (valid when the moduli are + co-prime) will be skipped. + + If the hint ``symmetric`` is True (default is False), the value of ``n`` + will be within 1/2 of the modulus, possibly negative. + + Examples + ======== + + >>> from sympy.ntheory.modular import solve_congruence + + What number is 2 mod 3, 3 mod 5 and 2 mod 7? + + >>> solve_congruence((2, 3), (3, 5), (2, 7)) + (23, 105) + >>> [23 % m for m in [3, 5, 7]] + [2, 3, 2] + + If you prefer to work with all remainder in one list and + all moduli in another, send the arguments like this: + + >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7))) + (23, 105) + + The moduli need not be co-prime; in this case there may or + may not be a solution: + + >>> solve_congruence((2, 3), (4, 6)) is None + True + + >>> solve_congruence((2, 3), (5, 6)) + (5, 6) + + The symmetric flag will make the result be within 1/2 of the modulus: + + >>> solve_congruence((2, 3), (5, 6), symmetric=True) + (-1, 6) + + See Also + ======== + + crt : high level routine implementing the Chinese Remainder Theorem + + """ + def combine(c1, c2): + """Return the tuple (a, m) which satisfies the requirement + that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution + """ + a1, m1 = c1 + a2, m2 = c2 + a, b, c = m1, a2 - a1, m2 + g = reduce(igcd, [a, b, c]) + a, b, c = [i//g for i in [a, b, c]] + if a != 1: + inv_a, _, g = igcdex(a, c) + if g != 1: + return None + b *= inv_a + a, m = a1 + m1*b, m1*c + return a, m + + rm = remainder_modulus_pairs + symmetric = hint.get('symmetric', False) + + if hint.get('check', True): + rm = [(as_int(r), as_int(m)) for r, m in rm] + + # ignore redundant pairs but raise an error otherwise; also + # make sure that a unique set of bases is sent to gf_crt if + # they are all prime. + # + # The routine will work out less-trivial violations and + # return None, e.g. for the pairs (1,3) and (14,42) there + # is no answer because 14 mod 42 (having a gcd of 14) implies + # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14) + # which, being 0 mod 3, is inconsistent with 1 mod 3. But to + # preprocess the input beyond checking of another pair with 42 + # or 3 as the modulus (for this example) is not necessary. + uniq = {} + for r, m in rm: + r %= m + if m in uniq: + if r != uniq[m]: + return None + continue + uniq[m] = r + rm = [(r, m) for m, r in uniq.items()] + del uniq + + # if the moduli are co-prime, the crt will be significantly faster; + # checking all pairs for being co-prime gets to be slow but a prime + # test is a good trade-off + if all(isprime(m) for r, m in rm): + r, m = list(zip(*rm)) + return crt(m, r, symmetric=symmetric, check=False) + + rv = (0, 1) + for rmi in rm: + rv = combine(rv, rmi) + if rv is None: + break + n, m = rv + n = n % m + else: + if symmetric: + return symmetric_residue(n, m), m + return n, m diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/multinomial.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec50fdb533be547b9a8e60dc47568965bf89436 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/multinomial.py @@ -0,0 +1,188 @@ +from sympy.utilities.misc import as_int + + +def binomial_coefficients(n): + """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where + :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`. + + Examples + ======== + + >>> from sympy.ntheory import binomial_coefficients + >>> binomial_coefficients(9) + {(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84, + (4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1} + + See Also + ======== + + binomial_coefficients_list, multinomial_coefficients + """ + n = as_int(n) + d = {(0, n): 1, (n, 0): 1} + a = 1 + for k in range(1, n//2 + 1): + a = (a * (n - k + 1))//k + d[k, n - k] = d[n - k, k] = a + return d + + +def binomial_coefficients_list(n): + """ Return a list of binomial coefficients as rows of the Pascal's + triangle. + + Examples + ======== + + >>> from sympy.ntheory import binomial_coefficients_list + >>> binomial_coefficients_list(9) + [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] + + See Also + ======== + + binomial_coefficients, multinomial_coefficients + """ + n = as_int(n) + d = [1] * (n + 1) + a = 1 + for k in range(1, n//2 + 1): + a = (a * (n - k + 1))//k + d[k] = d[n - k] = a + return d + + +def multinomial_coefficients(m, n): + r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}`` + where ``C_kn`` are multinomial coefficients such that + ``n=k1+k2+..+km``. + + Examples + ======== + + >>> from sympy.ntheory import multinomial_coefficients + >>> multinomial_coefficients(2, 5) # indirect doctest + {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1} + + Notes + ===== + + The algorithm is based on the following result: + + .. math:: + \binom{n}{k_1, \ldots, k_m} = + \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots} + + Code contributed to Sage by Yann Laigle-Chapuy, copied with permission + of the author. + + See Also + ======== + + binomial_coefficients_list, binomial_coefficients + """ + m = as_int(m) + n = as_int(n) + if not m: + if n: + return {} + return {(): 1} + if m == 2: + return binomial_coefficients(n) + if m >= 2*n and n > 1: + return dict(multinomial_coefficients_iterator(m, n)) + t = [n] + [0] * (m - 1) + r = {tuple(t): 1} + if n: + j = 0 # j will be the leftmost nonzero position + else: + j = m + # enumerate tuples in co-lex order + while j < m - 1: + # compute next tuple + tj = t[j] + if j: + t[j] = 0 + t[0] = tj + if tj > 1: + t[j + 1] += 1 + j = 0 + start = 1 + v = 0 + else: + j += 1 + start = j + 1 + v = r[tuple(t)] + t[j] += 1 + # compute the value + # NB: the initialization of v was done above + for k in range(start, m): + if t[k]: + t[k] -= 1 + v += r[tuple(t)] + t[k] += 1 + t[0] -= 1 + r[tuple(t)] = (v * tj) // (n - t[0]) + return r + + +def multinomial_coefficients_iterator(m, n, _tuple=tuple): + """multinomial coefficient iterator + + This routine has been optimized for `m` large with respect to `n` by taking + advantage of the fact that when the monomial tuples `t` are stripped of + zeros, their coefficient is the same as that of the monomial tuples from + ``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are + precomputed to save memory and time. + + >>> from sympy.ntheory.multinomial import multinomial_coefficients + >>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3) + >>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)] + True + + Examples + ======== + + >>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator + >>> it = multinomial_coefficients_iterator(20,3) + >>> next(it) + ((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1) + """ + m = as_int(m) + n = as_int(n) + if m < 2*n or n == 1: + mc = multinomial_coefficients(m, n) + yield from mc.items() + else: + mc = multinomial_coefficients(n, n) + mc1 = {} + for k, v in mc.items(): + mc1[_tuple(filter(None, k))] = v + mc = mc1 + + t = [n] + [0] * (m - 1) + t1 = _tuple(t) + b = _tuple(filter(None, t1)) + yield (t1, mc[b]) + if n: + j = 0 # j will be the leftmost nonzero position + else: + j = m + # enumerate tuples in co-lex order + while j < m - 1: + # compute next tuple + tj = t[j] + if j: + t[j] = 0 + t[0] = tj + if tj > 1: + t[j + 1] += 1 + j = 0 + else: + j += 1 + t[j] += 1 + + t[0] -= 1 + t1 = _tuple(t) + b = _tuple(filter(None, t1)) + yield (t1, mc[b]) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/partitions_.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/partitions_.py new file mode 100644 index 0000000000000000000000000000000000000000..73ea91a345091b2dff9fd24806f334c73cf7b04e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/partitions_.py @@ -0,0 +1,192 @@ +from mpmath.libmp import (fzero, from_int, from_rational, + fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub, + mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin) +from sympy.core.numbers import igcd +from .residue_ntheory import (_sqrt_mod_prime_power, + legendre_symbol, jacobi_symbol, is_quad_residue) + +import math + +def _pre(): + maxn = 10**5 + global _factor + global _totient + _factor = [0]*maxn + _totient = [1]*maxn + lim = int(maxn**0.5) + 5 + for i in range(2, lim): + if _factor[i] == 0: + for j in range(i*i, maxn, i): + if _factor[j] == 0: + _factor[j] = i + for i in range(2, maxn): + if _factor[i] == 0: + _factor[i] = i + _totient[i] = i-1 + continue + x = _factor[i] + y = i//x + if y % x == 0: + _totient[i] = _totient[y]*x + else: + _totient[i] = _totient[y]*(x - 1) + +def _a(n, k, prec): + """ Compute the inner sum in HRR formula [1]_ + + References + ========== + + .. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf + + """ + if k == 1: + return fone + + k1 = k + e = 0 + p = _factor[k] + while k1 % p == 0: + k1 //= p + e += 1 + k2 = k//k1 # k2 = p^e + v = 1 - 24*n + pi = mpf_pi(prec) + + if k1 == 1: + # k = p^e + if p == 2: + mod = 8*k + v = mod + v % mod + v = (v*pow(9, k - 1, mod)) % mod + m = _sqrt_mod_prime_power(v, 2, e + 3)[0] + arg = mpf_div(mpf_mul( + from_int(4*m), pi, prec), from_int(mod), prec) + return mpf_mul(mpf_mul( + from_int((-1)**e*jacobi_symbol(m - 1, m)), + mpf_sqrt(from_int(k), prec), prec), + mpf_sin(arg, prec), prec) + if p == 3: + mod = 3*k + v = mod + v % mod + if e > 1: + v = (v*pow(64, k//3 - 1, mod)) % mod + m = _sqrt_mod_prime_power(v, 3, e + 1)[0] + arg = mpf_div(mpf_mul(from_int(4*m), pi, prec), + from_int(mod), prec) + return mpf_mul(mpf_mul( + from_int(2*(-1)**(e + 1)*legendre_symbol(m, 3)), + mpf_sqrt(from_int(k//3), prec), prec), + mpf_sin(arg, prec), prec) + v = k + v % k + if v % p == 0: + if e == 1: + return mpf_mul( + from_int(jacobi_symbol(3, k)), + mpf_sqrt(from_int(k), prec), prec) + return fzero + if not is_quad_residue(v, p): + return fzero + _phi = p**(e - 1)*(p - 1) + v = (v*pow(576, _phi - 1, k)) + m = _sqrt_mod_prime_power(v, p, e)[0] + arg = mpf_div( + mpf_mul(from_int(4*m), pi, prec), + from_int(k), prec) + return mpf_mul(mpf_mul( + from_int(2*jacobi_symbol(3, k)), + mpf_sqrt(from_int(k), prec), prec), + mpf_cos(arg, prec), prec) + + if p != 2 or e >= 3: + d1, d2 = igcd(k1, 24), igcd(k2, 24) + e = 24//(d1*d2) + n1 = ((d2*e*n + (k2**2 - 1)//d1)* + pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1 + n2 = ((d1*e*n + (k1**2 - 1)//d2)* + pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2 + return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec) + if e == 2: + n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1 + n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4 + return mpf_mul(mpf_mul( + from_int(-1), + _a(n1, k1, prec), prec), + _a(n2, k2, prec)) + n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1 + n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2 + return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec) + +def _d(n, j, prec, sq23pi, sqrt8): + """ + Compute the sinh term in the outer sum of the HRR formula. + The constants sqrt(2/3*pi) and sqrt(8) must be precomputed. + """ + j = from_int(j) + pi = mpf_pi(prec) + a = mpf_div(sq23pi, j, prec) + b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec) + c = mpf_sqrt(b, prec) + ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec) + D = mpf_div( + mpf_sqrt(j, prec), + mpf_mul(mpf_mul(sqrt8, b), pi), prec) + E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec) + return mpf_mul(D, E) + + +def npartitions(n, verbose=False): + """ + Calculate the partition function P(n), i.e. the number of ways that + n can be written as a sum of positive integers. + + P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_. + + + The correctness of this implementation has been tested through $10^{10}$. + + Examples + ======== + + >>> from sympy.ntheory import npartitions + >>> npartitions(25) + 1958 + + References + ========== + + .. [1] https://mathworld.wolfram.com/PartitionFunctionP.html + + """ + n = int(n) + if n < 0: + return 0 + if n <= 5: + return [1, 1, 2, 3, 5, 7][n] + if '_factor' not in globals(): + _pre() + # Estimate number of bits in p(n). This formula could be tidied + pbits = int(( + math.pi*(2*n/3.)**0.5 - + math.log(4*n))/math.log(10) + 1) * \ + math.log(10, 2) + prec = p = int(pbits*1.1 + 100) + s = fzero + M = max(6, int(0.24*n**0.5 + 4)) + if M > 10**5: + raise ValueError("Input too big") # Corresponds to n > 1.7e11 + sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p) + sqrt8 = mpf_sqrt(from_int(8), p) + for q in range(1, M): + a = _a(n, q, p) + d = _d(n, q, p, sq23pi, sqrt8) + s = mpf_add(s, mpf_mul(a, d), prec) + if verbose: + print("step", q, "of", M, to_str(a, 10), to_str(d, 10)) + # On average, the terms decrease rapidly in magnitude. + # Dynamically reducing the precision greatly improves + # performance. + p = bitcount(abs(to_int(d))) + 50 + return int(to_int(mpf_add(s, fhalf, prec))) + +__all__ = ['npartitions'] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/primetest.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/primetest.py new file mode 100644 index 0000000000000000000000000000000000000000..1872ef6307ee705b0642cdf28d3deec8d8ca4148 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/primetest.py @@ -0,0 +1,696 @@ +""" +Primality testing + +""" + +from sympy.core.numbers import igcd +from sympy.core.power import integer_nthroot +from sympy.core.sympify import sympify +from sympy.external.gmpy import HAS_GMPY +from sympy.utilities.misc import as_int + +from mpmath.libmp import bitcount as _bitlength + + +def _int_tuple(*i): + return tuple(int(_) for _ in i) + + +def is_euler_pseudoprime(n, b): + """Returns True if n is prime or an Euler pseudoprime to base b, else False. + + Euler Pseudoprime : In arithmetic, an odd composite integer n is called an + euler pseudoprime to base a, if a and n are coprime and satisfy the modular + arithmetic congruence relation : + + a ^ (n-1)/2 = + 1(mod n) or + a ^ (n-1)/2 = - 1(mod n) + + (where mod refers to the modulo operation). + + Examples + ======== + + >>> from sympy.ntheory.primetest import is_euler_pseudoprime + >>> is_euler_pseudoprime(2, 5) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime + """ + from sympy.ntheory.factor_ import trailing + + if not mr(n, [b]): + return False + + n = as_int(n) + r = n - 1 + c = pow(b, r >> trailing(r), n) + + if c == 1: + return True + + while True: + if c == n - 1: + return True + c = pow(c, 2, n) + if c == 1: + return False + + +def is_square(n, prep=True): + """Return True if n == a * a for some integer a, else False. + If n is suspected of *not* being a square then this is a + quick method of confirming that it is not. + + Examples + ======== + + >>> from sympy.ntheory.primetest import is_square + >>> is_square(25) + True + >>> is_square(2) + False + + References + ========== + + .. [1] https://mersenneforum.org/showpost.php?p=110896 + + See Also + ======== + sympy.core.power.integer_nthroot + """ + if prep: + n = as_int(n) + if n < 0: + return False + if n in (0, 1): + return True + # def magic(n): + # s = {x**2 % n for x in range(n)} + # return sum(1 << bit for bit in s) + # >>> print(hex(magic(128))) + # 0x2020212020202130202021202030213 + # >>> print(hex(magic(99))) + # 0x209060049048220348a410213 + # >>> print(hex(magic(91))) + # 0x102e403012a0c9862c14213 + # >>> print(hex(magic(85))) + # 0x121065188e001c46298213 + if not 0x2020212020202130202021202030213 & (1 << (n & 127)): + return False # e.g. 2, 3 + m = n % (99 * 91 * 85) + if not 0x209060049048220348a410213 & (1 << (m % 99)): + return False # e.g. 17, 68 + if not 0x102e403012a0c9862c14213 & (1 << (m % 91)): + return False # e.g. 97, 388 + if not 0x121065188e001c46298213 & (1 << (m % 85)): + return False # e.g. 793, 1408 + # n is either: + # a) odd = 4*even + 1 (and square if even = k*(k + 1)) + # b) even with + # odd multiplicity of 2 --> not square, e.g. 39040 + # even multiplicity of 2, e.g. 4, 16, 36, ..., 16324 + # removal of factors of 2 to give an odd, and rejection if + # any(i%2 for i in divmod(odd - 1, 4)) + # will give an odd number in form 4*even + 1. + # Use of `trailing` to check the power of 2 is not done since it + # does not apply to a large percentage of arbitrary numbers + # and the integer_nthroot is able to quickly resolve these cases. + return integer_nthroot(n, 2)[1] + + +def _test(n, base, s, t): + """Miller-Rabin strong pseudoprime test for one base. + Return False if n is definitely composite, True if n is + probably prime, with a probability greater than 3/4. + + """ + # do the Fermat test + b = pow(base, t, n) + if b == 1 or b == n - 1: + return True + else: + for j in range(1, s): + b = pow(b, 2, n) + if b == n - 1: + return True + # see I. Niven et al. "An Introduction to Theory of Numbers", page 78 + if b == 1: + return False + return False + + +def mr(n, bases): + """Perform a Miller-Rabin strong pseudoprime test on n using a + given list of bases/witnesses. + + References + ========== + + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 135-138 + + A list of thresholds and the bases they require are here: + https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants + + Examples + ======== + + >>> from sympy.ntheory.primetest import mr + >>> mr(1373651, [2, 3]) + False + >>> mr(479001599, [31, 73]) + True + + """ + from sympy.ntheory.factor_ import trailing + from sympy.polys.domains import ZZ + + n = as_int(n) + if n < 2: + return False + # remove powers of 2 from n-1 (= t * 2**s) + s = trailing(n - 1) + t = n >> s + for base in bases: + # Bases >= n are wrapped, bases < 2 are invalid + if base >= n: + base %= n + if base >= 2: + base = ZZ(base) + if not _test(n, base, s, t): + return False + return True + + +def _lucas_sequence(n, P, Q, k): + """Return the modular Lucas sequence (U_k, V_k, Q_k). + + Given a Lucas sequence defined by P, Q, returns the kth values for + U and V, along with Q^k, all modulo n. This is intended for use with + possibly very large values of n and k, where the combinatorial functions + would be completely unusable. + + The modular Lucas sequences are used in numerous places in number theory, + especially in the Lucas compositeness tests and the various n + 1 proofs. + + Examples + ======== + + >>> from sympy.ntheory.primetest import _lucas_sequence + >>> N = 10**2000 + 4561 + >>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol + (0, 2, 1) + + """ + D = P*P - 4*Q + if n < 2: + raise ValueError("n must be >= 2") + if k < 0: + raise ValueError("k must be >= 0") + if D == 0: + raise ValueError("D must not be zero") + + if k == 0: + return _int_tuple(0, 2, Q) + U = 1 + V = P + Qk = Q + b = _bitlength(k) + if Q == 1: + # Optimization for extra strong tests. + while b > 1: + U = (U*V) % n + V = (V*V - 2) % n + b -= 1 + if (k >> (b - 1)) & 1: + U, V = U*P + V, V*P + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + elif P == 1 and Q == -1: + # Small optimization for 50% of Selfridge parameters. + while b > 1: + U = (U*V) % n + if Qk == 1: + V = (V*V - 2) % n + else: + V = (V*V + 2) % n + Qk = 1 + b -= 1 + if (k >> (b-1)) & 1: + U, V = U + V, V + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + Qk = -1 + else: + # The general case with any P and Q. + while b > 1: + U = (U*V) % n + V = (V*V - 2*Qk) % n + Qk *= Qk + b -= 1 + if (k >> (b - 1)) & 1: + U, V = U*P + V, V*P + U*D + if U & 1: + U += n + if V & 1: + V += n + U, V = U >> 1, V >> 1 + Qk *= Q + Qk %= n + return _int_tuple(U % n, V % n, Qk) + + +def _lucas_selfridge_params(n): + """Calculates the Selfridge parameters (D, P, Q) for n. This is + method A from page 1401 of Baillie and Wagstaff. + + References + ========== + .. [1] "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + """ + from sympy.ntheory.residue_ntheory import jacobi_symbol + D = 5 + while True: + g = igcd(abs(D), n) + if g > 1 and g != n: + return (0, 0, 0) + if jacobi_symbol(D, n) == -1: + break + if D > 0: + D = -D - 2 + else: + D = -D + 2 + return _int_tuple(D, 1, (1 - D)/4) + + +def _lucas_extrastrong_params(n): + """Calculates the "extra strong" parameters (D, P, Q) for n. + + References + ========== + .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes + https://oeis.org/A217719 + .. [1] https://en.wikipedia.org/wiki/Lucas_pseudoprime + """ + from sympy.ntheory.residue_ntheory import jacobi_symbol + P, Q, D = 3, 1, 5 + while True: + g = igcd(D, n) + if g > 1 and g != n: + return (0, 0, 0) + if jacobi_symbol(D, n) == -1: + break + P += 1 + D = P*P - 4 + return _int_tuple(D, P, Q) + + +def is_lucas_prp(n): + """Standard Lucas compositeness test with Selfridge parameters. Returns + False if n is definitely composite, and True if n is a Lucas probable + prime. + + This is typically used in combination with the Miller-Rabin test. + + References + ========== + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - OEIS A217120: Lucas Pseudoprimes + https://oeis.org/A217120 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_lucas_prp + >>> for i in range(10000): + ... if is_lucas_prp(i) and not isprime(i): + ... print(i) + 323 + 377 + 1159 + 1829 + 3827 + 5459 + 5777 + 9071 + 9179 + """ + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_selfridge_params(n) + if D == 0: + return False + U, V, Qk = _lucas_sequence(n, P, Q, n+1) + return U == 0 + + +def is_strong_lucas_prp(n): + """Strong Lucas compositeness test with Selfridge parameters. Returns + False if n is definitely composite, and True if n is a strong Lucas + probable prime. + + This is often used in combination with the Miller-Rabin test, and + in particular, when combined with M-R base 2 creates the strong BPSW test. + + References + ========== + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - OEIS A217255: Strong Lucas Pseudoprimes + https://oeis.org/A217255 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp + >>> for i in range(20000): + ... if is_strong_lucas_prp(i) and not isprime(i): + ... print(i) + 5459 + 5777 + 10877 + 16109 + 18971 + """ + from sympy.ntheory.factor_ import trailing + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_selfridge_params(n) + if D == 0: + return False + + # remove powers of 2 from n+1 (= k * 2**s) + s = trailing(n + 1) + k = (n+1) >> s + + U, V, Qk = _lucas_sequence(n, P, Q, k) + + if U == 0 or V == 0: + return True + for r in range(1, s): + V = (V*V - 2*Qk) % n + if V == 0: + return True + Qk = pow(Qk, 2, n) + return False + + +def is_extra_strong_lucas_prp(n): + """Extra Strong Lucas compositeness test. Returns False if n is + definitely composite, and True if n is a "extra strong" Lucas probable + prime. + + The parameters are selected using P = 3, Q = 1, then incrementing P until + (D|n) == -1. The test itself is as defined in Grantham 2000, from the + Mo and Jones preprint. The parameter selection and test are the same as + used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime + page on Wikipedia. + + With these parameters, there are no counterexamples below 2^64 nor any + known above that range. It is 20-50% faster than the strong test. + + Because of the different parameters selected, there is no relationship + between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes. + In particular, one is not a subset of the other. + + References + ========== + - "Frobenius Pseudoprimes", Jon Grantham, 2000. + https://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/ + - OEIS A217719: Extra Strong Lucas Pseudoprimes + https://oeis.org/A217719 + - https://en.wikipedia.org/wiki/Lucas_pseudoprime + + Examples + ======== + + >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp + >>> for i in range(20000): + ... if is_extra_strong_lucas_prp(i) and not isprime(i): + ... print(i) + 989 + 3239 + 5777 + 10877 + """ + # Implementation notes: + # 1) the parameters differ from Thomas R. Nicely's. His parameter + # selection leads to pseudoprimes that overlap M-R tests, and + # contradict Baillie and Wagstaff's suggestion of (D|n) = -1. + # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas + # sequence must have Q=1. See Grantham theorem 2.3, any of the + # references on the MathWorld page, or run it and see Q=-1 is wrong. + from sympy.ntheory.factor_ import trailing + n = as_int(n) + if n == 2: + return True + if n < 2 or (n % 2) == 0: + return False + if is_square(n, False): + return False + + D, P, Q = _lucas_extrastrong_params(n) + if D == 0: + return False + + # remove powers of 2 from n+1 (= k * 2**s) + s = trailing(n + 1) + k = (n+1) >> s + + U, V, Qk = _lucas_sequence(n, P, Q, k) + + if U == 0 and (V == 2 or V == n - 2): + return True + for r in range(1, s): + if V == 0: + return True + V = (V*V - 2) % n + return False + + +def isprime(n): + """ + Test if n is a prime number (True) or not (False). For n < 2^64 the + answer is definitive; larger n values have a small probability of actually + being pseudoprimes. + + Negative numbers (e.g. -2) are not considered prime. + + The first step is looking for trivial factors, which if found enables + a quick return. Next, if the sieve is large enough, use bisection search + on the sieve. For small numbers, a set of deterministic Miller-Rabin + tests are performed with bases that are known to have no counterexamples + in their range. Finally if the number is larger than 2^64, a strong + BPSW test is performed. While this is a probable prime test and we + believe counterexamples exist, there are no known counterexamples. + + Examples + ======== + + >>> from sympy.ntheory import isprime + >>> isprime(13) + True + >>> isprime(13.0) # limited precision + False + >>> isprime(15) + False + + Notes + ===== + + This routine is intended only for integer input, not numerical + expressions which may represent numbers. Floats are also + rejected as input because they represent numbers of limited + precision. While it is tempting to permit 7.0 to represent an + integer there are errors that may "pass silently" if this is + allowed: + + >>> from sympy import Float, S + >>> int(1e3) == 1e3 == 10**3 + True + >>> int(1e23) == 1e23 + True + >>> int(1e23) == 10**23 + False + + >>> near_int = 1 + S(1)/10**19 + >>> near_int == int(near_int) + False + >>> n = Float(near_int, 10) # truncated by precision + >>> n == int(n) + True + >>> n = Float(near_int, 20) + >>> n == int(n) + False + + See Also + ======== + + sympy.ntheory.generate.primerange : Generates all primes in a given range + sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n + sympy.ntheory.generate.prime : Return the nth prime + + References + ========== + - https://en.wikipedia.org/wiki/Strong_pseudoprime + - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. + http://mpqs.free.fr/LucasPseudoprimes.pdf + - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test + """ + try: + n = as_int(n) + except ValueError: + return False + + # Step 1, do quick composite testing via trial division. The individual + # modulo tests benchmark faster than one or two primorial igcds for me. + # The point here is just to speedily handle small numbers and many + # composites. Step 2 only requires that n <= 2 get handled here. + if n in [2, 3, 5]: + return True + if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0: + return False + if n < 49: + return True + if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \ + (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \ + (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0: + return False + if n < 2809: + return True + if n < 31417: + return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951, 23377] + + # bisection search on the sieve if the sieve is large enough + from sympy.ntheory.generate import sieve as s + if n <= s._list[-1]: + l, u = s.search(n) + return l == u + + # If we have GMPY2, skip straight to step 3 and do a strong BPSW test. + # This should be a bit faster than our step 2, and for large values will + # be a lot faster than our step 3 (C+GMP vs. Python). + if HAS_GMPY == 2: + from gmpy2 import is_strong_prp, is_strong_selfridge_prp + return is_strong_prp(n, 2) and is_strong_selfridge_prp(n) + + + # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See: + # https://miller-rabin.appspot.com/ + # for lists. We have made sure the M-R routine will successfully handle + # bases larger than n, so we can use the minimal set. + # In September 2015 deterministic numbers were extended to over 2^81. + # https://arxiv.org/pdf/1509.00864.pdf + # https://oeis.org/A014233 + if n < 341531: + return mr(n, [9345883071009581737]) + if n < 885594169: + return mr(n, [725270293939359937, 3569819667048198375]) + if n < 350269456337: + return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375]) + if n < 55245642489451: + return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650]) + if n < 7999252175582851: + return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805]) + if n < 585226005592931977: + return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375]) + if n < 18446744073709551616: + return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) + if n < 318665857834031151167461: + return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]) + if n < 3317044064679887385961981: + return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]) + + # We could do this instead at any point: + #if n < 18446744073709551616: + # return mr(n, [2]) and is_extra_strong_lucas_prp(n) + + # Here are tests that are safe for MR routines that don't understand + # large bases. + #if n < 9080191: + # return mr(n, [31, 73]) + #if n < 19471033: + # return mr(n, [2, 299417]) + #if n < 38010307: + # return mr(n, [2, 9332593]) + #if n < 316349281: + # return mr(n, [11000544, 31481107]) + #if n < 4759123141: + # return mr(n, [2, 7, 61]) + #if n < 105936894253: + # return mr(n, [2, 1005905886, 1340600841]) + #if n < 31858317218647: + # return mr(n, [2, 642735, 553174392, 3046413974]) + #if n < 3071837692357849: + # return mr(n, [2, 75088, 642735, 203659041, 3613982119]) + #if n < 18446744073709551616: + # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) + + # Step 3: BPSW. + # + # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed + # 44.0s old isprime using 46 bases + # 5.3s strong BPSW + one random base + # 4.3s extra strong BPSW + one random base + # 4.1s strong BPSW + # 3.2s extra strong BPSW + + # Classic BPSW from page 1401 of the paper. See alternate ideas below. + return mr(n, [2]) and is_strong_lucas_prp(n) + + # Using extra strong test, which is somewhat faster + #return mr(n, [2]) and is_extra_strong_lucas_prp(n) + + # Add a random M-R base + #import random + #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n) + + +def is_gaussian_prime(num): + r"""Test if num is a Gaussian prime number. + + References + ========== + + .. [1] https://oeis.org/wiki/Gaussian_primes + """ + + num = sympify(num) + a, b = num.as_real_imag() + a = as_int(a, strict=False) + b = as_int(b, strict=False) + if a == 0: + b = abs(b) + return isprime(b) and b % 4 == 3 + elif b == 0: + a = abs(a) + return isprime(a) and a % 4 == 3 + return isprime(a**2 + b**2) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/qs.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/qs.py new file mode 100644 index 0000000000000000000000000000000000000000..993a8e33fe8aa588f9953970a6f238ad3b7d363b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/qs.py @@ -0,0 +1,515 @@ +from sympy.core.numbers import igcd, mod_inverse +from sympy.core.power import integer_nthroot +from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power +from sympy.ntheory import isprime +from math import log, sqrt +import random + +rgen = random.Random() + +class SievePolynomial: + def __init__(self, modified_coeff=(), a=None, b=None): + """This class denotes the seive polynomial. + If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded + to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient + is stored in the form `[a**2, 2*a*b, b**2 - N]`. This + ensures faster `eval` method because we dont have to + perform `a**2, 2*a*b, b**2` every time we call the + `eval` method. As multiplication is more expensive + than addition, by using modified_coefficient we get + a faster seiving process. + + Parameters + ========== + + modified_coeff : modified_coefficient of sieve polynomial + a : parameter of the sieve polynomial + b : parameter of the sieve polynomial + """ + self.modified_coeff = modified_coeff + self.a = a + self.b = b + + def eval(self, x): + """ + Compute the value of the sieve polynomial at point x. + + Parameters + ========== + + x : Integer parameter for sieve polynomial + """ + ans = 0 + for coeff in self.modified_coeff: + ans *= x + ans += coeff + return ans + + +class FactorBaseElem: + """This class stores an element of the `factor_base`. + """ + def __init__(self, prime, tmem_p, log_p): + """ + Initialization of factor_base_elem. + + Parameters + ========== + + prime : prime number of the factor_base + tmem_p : Integer square root of x**2 = n mod prime + log_p : Compute Natural Logarithm of the prime + """ + self.prime = prime + self.tmem_p = tmem_p + self.log_p = log_p + self.soln1 = None + self.soln2 = None + self.a_inv = None + self.b_ainv = None + + +def _generate_factor_base(prime_bound, n): + """Generate `factor_base` for Quadratic Sieve. The `factor_base` + consists of all the points whose ``legendre_symbol(n, p) == 1`` + and ``p < num_primes``. Along with the prime `factor_base` also stores + natural logarithm of prime and the residue n modulo p. + It also returns the of primes numbers in the `factor_base` which are + close to 1000 and 5000. + + Parameters + ========== + + prime_bound : upper prime bound of the factor_base + n : integer to be factored + """ + from sympy.ntheory.generate import sieve + factor_base = [] + idx_1000, idx_5000 = None, None + for prime in sieve.primerange(1, prime_bound): + if pow(n, (prime - 1) // 2, prime) == 1: + if prime > 1000 and idx_1000 is None: + idx_1000 = len(factor_base) - 1 + if prime > 5000 and idx_5000 is None: + idx_5000 = len(factor_base) - 1 + residue = _sqrt_mod_prime_power(n, prime, 1)[0] + log_p = round(log(prime)*2**10) + factor_base.append(FactorBaseElem(prime, residue, log_p)) + return idx_1000, idx_5000, factor_base + + +def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None): + """This step is the initialization of the 1st sieve polynomial. + Here `a` is selected as a product of several primes of the factor_base + such that `a` is about to ``sqrt(2*N) / M``. Other initial values of + factor_base elem are also initialized which includes a_inv, b_ainv, soln1, + soln2 which are used when the sieve polynomial is changed. The b_ainv + is required for fast polynomial change as we do not have to calculate + `2*b*mod_inverse(a, prime)` every time. + We also ensure that the `factor_base` primes which make `a` are between + 1000 and 5000. + + Parameters + ========== + + N : Number to be factored + M : sieve interval + factor_base : factor_base primes + idx_1000 : index of prime number in the factor_base near 1000 + idx_5000 : index of prime number in the factor_base near to 5000 + seed : Generate pseudoprime numbers + """ + if seed is not None: + rgen.seed(seed) + approx_val = sqrt(2*N) / M + # `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a` + # randomly search for a combination of primes whose multiplication is close to approx_val + # This multiplication of primes will be `a` and the primes will be `q` + # `best_a` denotes that `a` is close to approx_val in the random search of combination + best_a, best_q, best_ratio = None, None, None + start = 0 if idx_1000 is None else idx_1000 + end = len(factor_base) - 1 if idx_5000 is None else idx_5000 + for _ in range(50): + a = 1 + q = [] + while(a < approx_val): + rand_p = 0 + while(rand_p == 0 or rand_p in q): + rand_p = rgen.randint(start, end) + p = factor_base[rand_p].prime + a *= p + q.append(rand_p) + ratio = a / approx_val + if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1): + best_q = q + best_a = a + best_ratio = ratio + + a = best_a + q = best_q + + B = [] + for idx, val in enumerate(q): + q_l = factor_base[val].prime + gamma = factor_base[val].tmem_p * mod_inverse(a // q_l, q_l) % q_l + if gamma > q_l / 2: + gamma = q_l - gamma + B.append(a//q_l*gamma) + + b = sum(B) + g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) + + for fb in factor_base: + if a % fb.prime == 0: + continue + fb.a_inv = mod_inverse(a, fb.prime) + fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B] + fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime + fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime + return g, B + + +def _initialize_ith_poly(N, factor_base, i, g, B): + """Initialization stage of ith poly. After we finish sieving 1`st polynomial + here we quickly change to the next polynomial from which we will again + start sieving. Suppose we generated ith sieve polynomial and now we + want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1`` + where `j` is the number of prime factors of the coefficient `a` + then this function can be used to go to the next polynomial. If + ``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage. + + Parameters + ========== + + N : number to be factored + factor_base : factor_base primes + i : integer denoting ith polynomial + g : (i - 1)th polynomial + B : array that stores a//q_l*gamma + """ + from sympy.functions.elementary.integers import ceiling + v = 1 + j = i + while(j % 2 == 0): + v += 1 + j //= 2 + if ceiling(i / (2**v)) % 2 == 1: + neg_pow = -1 + else: + neg_pow = 1 + b = g.b + 2*neg_pow*B[v - 1] + a = g.a + g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) + for fb in factor_base: + if a % fb.prime == 0: + continue + fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime + fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime + + return g + + +def _gen_sieve_array(M, factor_base): + """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base + that does not divide the coefficient `a` we add log_p over the sieve_array + such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i` + is an integer. When p = 2 then log_p is only added using + ``-M <= soln1 + i*p <= M``. + + Parameters + ========== + + M : sieve interval + factor_base : factor_base primes + """ + sieve_array = [0]*(2*M + 1) + for factor in factor_base: + if factor.soln1 is None: #The prime does not divides a + continue + for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime): + sieve_array[idx] += factor.log_p + if factor.prime == 2: + continue + #if prime is 2 then sieve only with soln_1_p + for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime): + sieve_array[idx] += factor.log_p + return sieve_array + + +def _check_smoothness(num, factor_base): + """Here we check that if `num` is a smooth number or not. If `a` is a smooth + number then it returns a vector of prime exponents modulo 2. For example + if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then + `a` is a smooth number and this function returns ([1, 0, 0, 1], True). If + `a` is a partial relation which means that `a` a has one prime factor + greater than the `factor_base` then it returns `(a, False)` which denotes `a` + is a partial relation. + + Parameters + ========== + + a : integer whose smootheness is to be checked + factor_base : factor_base primes + """ + vec = [] + if num < 0: + vec.append(1) + num *= -1 + else: + vec.append(0) + #-1 is not included in factor_base add -1 in vector + for factor in factor_base: + if num % factor.prime != 0: + vec.append(0) + continue + factor_exp = 0 + while num % factor.prime == 0: + factor_exp += 1 + num //= factor.prime + vec.append(factor_exp % 2) + if num == 1: + return vec, True + if isprime(num): + return num, False + return None, None + + +def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM): + """Trial division stage. Here we trial divide the values generetated + by sieve_poly in the sieve interval and if it is a smooth number then + it is stored in `smooth_relations`. Moreover, if we find two partial relations + with same large prime then they are combined to form a smooth relation. + First we iterate over sieve array and look for values which are greater + than accumulated_val, as these values have a high chance of being smooth + number. Then using these values we find smooth relations. + In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations + with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN`` + to form a smooth relation. + + Parameters + ========== + + N : Number to be factored + M : sieve interval + factor_base : factor_base primes + sieve_array : stores log_p values + sieve_poly : polynomial from which we find smooth relations + partial_relations : stores partial relations with one large prime + ERROR_TERM : error term for accumulated_val + """ + sqrt_n = sqrt(float(N)) + accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM + smooth_relations = [] + proper_factor = set() + partial_relation_upper_bound = 128*factor_base[-1].prime + for idx, val in enumerate(sieve_array): + if val < accumulated_val: + continue + x = idx - M + v = sieve_poly.eval(x) + vec, is_smooth = _check_smoothness(v, factor_base) + if is_smooth is None:#Neither smooth nor partial + continue + u = sieve_poly.a*x + sieve_poly.b + # Update the partial relation + # If 2 partial relation with same large prime is found then generate smooth relation + if is_smooth is False:#partial relation found + large_prime = vec + #Consider the large_primes under 128*F + if large_prime > partial_relation_upper_bound: + continue + if large_prime not in partial_relations: + partial_relations[large_prime] = (u, v) + continue + else: + u_prev, v_prev = partial_relations[large_prime] + partial_relations.pop(large_prime) + try: + large_prime_inv = mod_inverse(large_prime, N) + except ValueError:#if large_prine divides N + proper_factor.add(large_prime) + continue + u = u*u_prev*large_prime_inv + v = v*v_prev // (large_prime*large_prime) + vec, is_smooth = _check_smoothness(v, factor_base) + #assert u*u % N == v % N + smooth_relations.append((u, v, vec)) + return smooth_relations, proper_factor + + +#LINEAR ALGEBRA STAGE +def _build_matrix(smooth_relations): + """Build a 2D matrix from smooth relations. + + Parameters + ========== + + smooth_relations : Stores smooth relations + """ + matrix = [] + for s_relation in smooth_relations: + matrix.append(s_relation[2]) + return matrix + + +def _gauss_mod_2(A): + """Fast gaussian reduction for modulo 2 matrix. + + Parameters + ========== + + A : Matrix + + Examples + ======== + + >>> from sympy.ntheory.qs import _gauss_mod_2 + >>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]]) + ([[[1, 0, 1], 3]], + [True, True, True, False], + [[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]]) + + Reference + ========== + + .. [1] A fast algorithm for gaussian elimination over GF(2) and + its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige""" + import copy + matrix = copy.deepcopy(A) + row = len(matrix) + col = len(matrix[0]) + mark = [False]*row + for c in range(col): + for r in range(row): + if matrix[r][c] == 1: + break + mark[r] = True + for c1 in range(col): + if c1 == c: + continue + if matrix[r][c1] == 1: + for r2 in range(row): + matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2 + dependent_row = [] + for idx, val in enumerate(mark): + if val == False: + dependent_row.append([matrix[idx], idx]) + return dependent_row, mark, matrix + + +def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N): + """Finds proper factor of N. Here, transform the dependent rows as a + combination of independent rows of the gauss_matrix to form the desired + relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation + we obtain a proper factor of N by `gcd(X - Y, N)`. + + Parameters + ========== + + dependent_rows : denoted dependent rows in the reduced matrix form + mark : boolean array to denoted dependent and independent rows + gauss_matrix : Reduced form of the smooth relations matrix + index : denoted the index of the dependent_rows + smooth_relations : Smooth relations vectors matrix + N : Number to be factored + """ + idx_in_smooth = dependent_rows[index][1] + independent_u = [smooth_relations[idx_in_smooth][0]] + independent_v = [smooth_relations[idx_in_smooth][1]] + dept_row = dependent_rows[index][0] + + for idx, val in enumerate(dept_row): + if val == 1: + for row in range(len(gauss_matrix)): + if gauss_matrix[row][idx] == 1 and mark[row] == True: + independent_u.append(smooth_relations[row][0]) + independent_v.append(smooth_relations[row][1]) + break + + u = 1 + v = 1 + for i in independent_u: + u *= i + for i in independent_v: + v *= i + #assert u**2 % N == v % N + v = integer_nthroot(v, 2)[0] + return igcd(u - v, N) + + +def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234): + """Performs factorization using Self-Initializing Quadratic Sieve. + In SIQS, let N be a number to be factored, and this N should not be a + perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and + ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N. + In order to find these integers X and Y we try to find relations of form + t**2 = u modN where u is a product of small primes. If we have enough of + these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that + the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``. + + Here, several optimizations are done like using multiple polynomials for + sieving, fast changing between polynomials and using partial relations. + The use of partial relations can speeds up the factoring by 2 times. + + Parameters + ========== + + N : Number to be Factored + prime_bound : upper bound for primes in the factor base + M : Sieve Interval + ERROR_TERM : Error term for checking smoothness + threshold : Extra smooth relations for factorization + seed : generate pseudo prime numbers + + Examples + ======== + + >>> from sympy.ntheory import qs + >>> qs(25645121643901801, 2000, 10000) + {5394769, 4753701529} + >>> qs(9804659461513846513, 2000, 10000) + {4641991, 2112166839943} + + References + ========== + + .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf + .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve + """ + ERROR_TERM*=2**10 + rgen.seed(seed) + idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N) + smooth_relations = [] + ith_poly = 0 + partial_relations = {} + proper_factor = set() + threshold = 5*len(factor_base) // 100 + while True: + if ith_poly == 0: + ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000) + else: + ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array) + ith_poly += 1 + if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial + ith_poly = 0 + sieve_array = _gen_sieve_array(M, factor_base) + s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM) + smooth_relations += s_rel + proper_factor |= p_f + if len(smooth_relations) >= len(factor_base) + threshold: + break + matrix = _build_matrix(smooth_relations) + dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) + N_copy = N + for index in range(len(dependent_row)): + factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N) + if factor > 1 and factor < N: + proper_factor.add(factor) + while(N_copy % factor == 0): + N_copy //= factor + if isprime(N_copy): + proper_factor.add(N_copy) + break + if(N_copy == 1): + break + return proper_factor diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..cba4735556cccc6cd1842877f6ec63a1e693c686 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py @@ -0,0 +1,1573 @@ +from __future__ import annotations + +from sympy.core.function import Function +from sympy.core.numbers import igcd, igcdex, mod_inverse +from sympy.core.power import isqrt +from sympy.core.singleton import S +from sympy.polys import Poly +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence +from .primetest import isprime +from .factor_ import factorint, trailing, totient, multiplicity, perfect_power +from sympy.utilities.misc import as_int +from sympy.core.random import _randint, randint + +from itertools import cycle, product + + +def n_order(a, n): + """Returns the order of ``a`` modulo ``n``. + + The order of ``a`` modulo ``n`` is the smallest integer + ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. + + Parameters + ========== + + a : integer + n : integer, n > 1. a and n should be relatively prime + + Examples + ======== + + >>> from sympy.ntheory import n_order + >>> n_order(3, 7) + 6 + >>> n_order(4, 7) + 3 + """ + from collections import defaultdict + a, n = as_int(a), as_int(n) + if n <= 1: + raise ValueError("n should be an integer greater than 1") + a = a % n + # Trivial + if a == 1: + return 1 + if igcd(a, n) != 1: + raise ValueError("The two numbers should be relatively prime") + # We want to calculate + # order = totient(n), factors = factorint(order) + factors = defaultdict(int) + for px, kx in factorint(n).items(): + if kx > 1: + factors[px] += kx - 1 + for py, ky in factorint(px - 1).items(): + factors[py] += ky + order = 1 + for px, kx in factors.items(): + order *= px**kx + # Now the `order` is the order of the group. + # The order of `a` divides the order of the group. + for p, e in factors.items(): + for _ in range(e): + if pow(a, order // p, n) == 1: + order //= p + else: + break + return order + + +def _primitive_root_prime_iter(p): + """ + Generates the primitive roots for a prime ``p`` + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter + >>> list(_primitive_root_prime_iter(19)) + [2, 3, 10, 13, 14, 15] + + References + ========== + + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 + + """ + # it is assumed that p is an int + v = [(p - 1) // i for i in factorint(p - 1).keys()] + a = 2 + while a < p: + for pw in v: + # a TypeError below may indicate that p was not an int + if pow(a, pw, p) == 1: + break + else: + yield a + a += 1 + + +def primitive_root(p): + """ + Returns the smallest primitive root or None. + + Parameters + ========== + + p : positive integer + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import primitive_root + >>> primitive_root(19) + 2 + + References + ========== + + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 + .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C + + """ + p = as_int(p) + if p < 1: + raise ValueError('p is required to be positive') + if p <= 2: + return 1 + f = factorint(p) + if len(f) > 2: + return None + if len(f) == 2: + if 2 not in f or f[2] > 1: + return None + + # case p = 2*p1**k, p1 prime + for p1, e1 in f.items(): + if p1 != 2: + break + i = 1 + while i < p: + i += 2 + if i % p1 == 0: + continue + if is_primitive_root(i, p): + return i + + else: + if 2 in f: + if p == 4: + return 3 + return None + p1, n = list(f.items())[0] + if n > 1: + # see Ref [2], page 81 + g = primitive_root(p1) + if is_primitive_root(g, p1**2): + return g + else: + for i in range(2, g + p1 + 1): + if igcd(i, p) == 1 and is_primitive_root(i, p): + return i + + return next(_primitive_root_prime_iter(p)) + + +def is_primitive_root(a, p): + """ + Returns True if ``a`` is a primitive root of ``p``. + + ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and + totient(p) is the smallest positive number s.t. + + a**totient(p) cong 1 mod(p) + + Parameters + ========== + + a : integer + p : integer, p > 1. a and p should be relatively prime + + Examples + ======== + + >>> from sympy.ntheory import is_primitive_root, n_order, totient + >>> is_primitive_root(3, 10) + True + >>> is_primitive_root(9, 10) + False + >>> n_order(3, 10) == totient(10) + True + >>> n_order(9, 10) == totient(10) + False + + """ + a, p = as_int(a), as_int(p) + if p <= 1: + raise ValueError("p should be an integer greater than 1") + a = a % p + if igcd(a, p) != 1: + raise ValueError("The two numbers should be relatively prime") + # Primitive root of p exist only for + # p = 2, 4, q**e, 2*q**e (q is odd prime) + if p <= 4: + # The primitive root is only p-1. + return a == p - 1 + t = trailing(p) + if t > 1: + return False + q = p >> t + if isprime(q): + group_order = q - 1 + factors = set(factorint(q - 1).keys()) + else: + m = perfect_power(q) + if not m: + return False + q, e = m + if not isprime(q): + return False + group_order = q**(e - 1)*(q - 1) + factors = set(factorint(q - 1).keys()) + factors.add(q) + return all(pow(a, group_order // prime, p) != 1 for prime in factors) + + +def _sqrt_mod_tonelli_shanks(a, p): + """ + Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` + + References + ========== + + .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 + + """ + s = trailing(p - 1) + t = p >> s + # find a non-quadratic residue + while 1: + d = randint(2, p - 1) + r = legendre_symbol(d, p) + if r == -1: + break + #assert legendre_symbol(d, p) == -1 + A = pow(a, t, p) + D = pow(d, t, p) + m = 0 + for i in range(s): + adm = A*pow(D, m, p) % p + adm = pow(adm, 2**(s - 1 - i), p) + if adm % p == p - 1: + m += 2**i + #assert A*pow(D, m, p) % p == 1 + x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p + return x + + +def sqrt_mod(a, p, all_roots=False): + """ + Find a root of ``x**2 = a mod p``. + + Parameters + ========== + + a : integer + p : positive integer + all_roots : if True the list of roots is returned or None + + Notes + ===== + + If there is no root it is returned None; else the returned root + is less or equal to ``p // 2``; in general is not the smallest one. + It is returned ``p // 2`` only if it is the only root. + + Use ``all_roots`` only when it is expected that all the roots fit + in memory; otherwise use ``sqrt_mod_iter``. + + Examples + ======== + + >>> from sympy.ntheory import sqrt_mod + >>> sqrt_mod(11, 43) + 21 + >>> sqrt_mod(17, 32, True) + [7, 9, 23, 25] + """ + if all_roots: + return sorted(sqrt_mod_iter(a, p)) + try: + p = abs(as_int(p)) + it = sqrt_mod_iter(a, p) + r = next(it) + if r > p // 2: + return p - r + elif r < p // 2: + return r + else: + try: + r = next(it) + if r > p // 2: + return p - r + except StopIteration: + pass + return r + except StopIteration: + return None + + +def _product(*iters): + """ + Cartesian product generator + + Notes + ===== + + Unlike itertools.product, it works also with iterables which do not fit + in memory. See https://bugs.python.org/issue10109 + + Author: Fernando Sumudu + with small changes + """ + inf_iters = tuple(cycle(enumerate(it)) for it in iters) + num_iters = len(inf_iters) + cur_val = [None]*num_iters + + first_v = True + while True: + i, p = 0, num_iters + while p and not i: + p -= 1 + i, cur_val[p] = next(inf_iters[p]) + + if not p and not i: + if first_v: + first_v = False + else: + break + + yield cur_val + + +def sqrt_mod_iter(a, p, domain=int): + """ + Iterate over solutions to ``x**2 = a mod p``. + + Parameters + ========== + + a : integer + p : positive integer + domain : integer domain, ``int``, ``ZZ`` or ``Integer`` + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter + >>> list(sqrt_mod_iter(11, 43)) + [21, 22] + """ + a, p = as_int(a), abs(as_int(p)) + if isprime(p): + a = a % p + if a == 0: + res = _sqrt_mod1(a, p, 1) + else: + res = _sqrt_mod_prime_power(a, p, 1) + if res: + if domain is ZZ: + yield from res + else: + for x in res: + yield domain(x) + else: + f = factorint(p) + v = [] + pv = [] + for px, ex in f.items(): + if a % px == 0: + rx = _sqrt_mod1(a, px, ex) + if not rx: + return + else: + rx = _sqrt_mod_prime_power(a, px, ex) + if not rx: + return + v.append(rx) + pv.append(px**ex) + mm, e, s = gf_crt1(pv, ZZ) + if domain is ZZ: + for vx in _product(*v): + r = gf_crt2(vx, pv, mm, e, s, ZZ) + yield r + else: + for vx in _product(*v): + r = gf_crt2(vx, pv, mm, e, s, ZZ) + yield domain(r) + + +def _sqrt_mod_prime_power(a, p, k): + """ + Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` + + Parameters + ========== + + a : integer + p : prime number + k : positive integer + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power + >>> _sqrt_mod_prime_power(11, 43, 1) + [21, 22] + + References + ========== + + .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 + .. [2] http://www.numbertheory.org/php/squareroot.html + .. [3] [Gathen99]_ + """ + pk = p**k + a = a % pk + + if k == 1: + if p == 2: + return [ZZ(a)] + if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1): + return None + + if p % 4 == 3: + res = pow(a, (p + 1) // 4, p) + elif p % 8 == 5: + sign = pow(a, (p - 1) // 4, p) + if sign == 1: + res = pow(a, (p + 3) // 8, p) + else: + b = pow(4*a, (p - 5) // 8, p) + x = (2*a*b) % p + if pow(x, 2, p) == a: + res = x + else: + res = _sqrt_mod_tonelli_shanks(a, p) + + # ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic; + # sort to get always the same result + return sorted([ZZ(res), ZZ(p - res)]) + + if k > 1: + # see Ref.[2] + if p == 2: + if a % 8 != 1: + return None + if k <= 3: + s = set() + for i in range(0, pk, 4): + s.add(1 + i) + s.add(-1 + i) + return list(s) + # according to Ref.[2] for k > 2 there are two solutions + # (mod 2**k-1), that is four solutions (mod 2**k), which can be + # obtained from the roots of x**2 = 0 (mod 8) + rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)] + # hensel lift them to solutions of x**2 = 0 (mod 2**k) + # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1) + # then r + 2**(nx - 1) is a root mod 2**(nx+1) + n = 3 + res = [] + for r in rv: + nx = n + while nx < k: + r1 = (r**2 - a) >> nx + if r1 % 2: + r = r + (1 << (nx - 1)) + #assert (r**2 - a)% (1 << (nx + 1)) == 0 + nx += 1 + if r not in res: + res.append(r) + x = r + (1 << (k - 1)) + #assert (x**2 - a) % pk == 0 + if x < (1 << nx) and x not in res: + if (x**2 - a) % pk == 0: + res.append(x) + return res + rv = _sqrt_mod_prime_power(a, p, 1) + if not rv: + return None + r = rv[0] + fr = r**2 - a + # hensel lifting with Newton iteration, see Ref.[3] chapter 9 + # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2 + n = 1 + px = p + while 1: + n1 = n + n1 *= 2 + if n1 > k: + break + n = n1 + px = px**2 + frinv = igcdex(2*r, px)[0] + r = (r - fr*frinv) % px + fr = r**2 - a + if n < k: + px = p**k + frinv = igcdex(2*r, px)[0] + r = (r - fr*frinv) % px + return [r, px - r] + + +def _sqrt_mod1(a, p, n): + """ + Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` + + see http://www.numbertheory.org/php/squareroot.html + """ + pn = p**n + a = a % pn + if a == 0: + # case gcd(a, p**k) = p**n + m = n // 2 + if n % 2 == 1: + pm1 = p**(m + 1) + def _iter0a(): + i = 0 + while i < pn: + yield i + i += pm1 + return _iter0a() + else: + pm = p**m + def _iter0b(): + i = 0 + while i < pn: + yield i + i += pm + return _iter0b() + + # case gcd(a, p**k) = p**r, r < n + f = factorint(a) + r = f[p] + if r % 2 == 1: + return None + m = r // 2 + a1 = a >> r + if p == 2: + if n - r == 1: + pnm1 = 1 << (n - m + 1) + pm1 = 1 << (m + 1) + def _iter1(): + k = 1 << (m + 2) + i = 1 << m + while i < pnm1: + j = i + while j < pn: + yield j + j += k + i += pm1 + return _iter1() + if n - r == 2: + res = _sqrt_mod_prime_power(a1, p, n - r) + if res is None: + return None + pnm = 1 << (n - m) + def _iter2(): + s = set() + for r in res: + i = 0 + while i < pn: + x = (r << m) + i + if x not in s: + s.add(x) + yield x + i += pnm + return _iter2() + if n - r > 2: + res = _sqrt_mod_prime_power(a1, p, n - r) + if res is None: + return None + pnm1 = 1 << (n - m - 1) + def _iter3(): + s = set() + for r in res: + i = 0 + while i < pn: + x = ((r << m) + i) % pn + if x not in s: + s.add(x) + yield x + i += pnm1 + return _iter3() + else: + m = r // 2 + a1 = a // p**r + res1 = _sqrt_mod_prime_power(a1, p, n - r) + if res1 is None: + return None + pm = p**m + pnr = p**(n-r) + pnm = p**(n-m) + + def _iter4(): + s = set() + pm = p**m + for rx in res1: + i = 0 + while i < pnm: + x = ((rx + i) % pn) + if x not in s: + s.add(x) + yield x*pm + i += pnr + return _iter4() + + +def is_quad_residue(a, p): + """ + Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, + i.e a % p in set([i**2 % p for i in range(p)]). + + Examples + ======== + + If ``p`` is an odd + prime, an iterative method is used to make the determination: + + >>> from sympy.ntheory import is_quad_residue + >>> sorted(set([i**2 % 7 for i in range(7)])) + [0, 1, 2, 4] + >>> [j for j in range(7) if is_quad_residue(j, 7)] + [0, 1, 2, 4] + + See Also + ======== + + legendre_symbol, jacobi_symbol + """ + a, p = as_int(a), as_int(p) + if p < 1: + raise ValueError('p must be > 0') + if a >= p or a < 0: + a = a % p + if a < 2 or p < 3: + return True + if not isprime(p): + if p % 2 and jacobi_symbol(a, p) == -1: + return False + r = sqrt_mod(a, p) + if r is None: + return False + else: + return True + + return pow(a, (p - 1) // 2, p) == 1 + + +def is_nthpow_residue(a, n, m): + """ + Returns True if ``x**n == a (mod m)`` has solutions. + + References + ========== + + .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 + + """ + a = a % m + a, n, m = as_int(a), as_int(n), as_int(m) + if m <= 0: + raise ValueError('m must be > 0') + if n < 0: + raise ValueError('n must be >= 0') + if n == 0: + if m == 1: + return False + return a == 1 + if a == 0: + return True + if n == 1: + return True + if n == 2: + return is_quad_residue(a, m) + return _is_nthpow_residue_bign(a, n, m) + + +def _is_nthpow_residue_bign(a, n, m): + r"""Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`.""" + # assert n > 2 + # assert a > 0 and m > 0 + if primitive_root(m) is None or igcd(a, m) != 1: + # assert m >= 8 + for prime, power in factorint(m).items(): + if not _is_nthpow_residue_bign_prime_power(a, n, prime, power): + return False + return True + f = totient(m) + k = int(f // igcd(f, n)) + return pow(a, k, int(m)) == 1 + + +def _is_nthpow_residue_bign_prime_power(a, n, p, k): + r"""Returns True/False if a solution for `x^n = a \pmod{p^k}` + does/does not exist.""" + # assert a > 0 + # assert n > 2 + # assert p is prime + # assert k > 0 + if a % p: + if p != 2: + return _is_nthpow_residue_bign(a, n, pow(p, k)) + if n & 1: + return True + c = trailing(n) + return a % pow(2, min(c + 2, k)) == 1 + else: + a %= pow(p, k) + if not a: + return True + mu = multiplicity(p, a) + if mu % n: + return False + pm = pow(p, mu) + return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu) + + +def _nthroot_mod2(s, q, p): + f = factorint(q) + v = [] + for b, e in f.items(): + v.extend([b]*e) + for qx in v: + s = _nthroot_mod1(s, qx, p, False) + return s + + +def _nthroot_mod1(s, q, p, all_roots): + """ + Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` + + References + ========== + + .. [1] A. M. Johnston "A Generalized qth Root Algorithm" + + """ + g = primitive_root(p) + if not isprime(q): + r = _nthroot_mod2(s, q, p) + else: + f = p - 1 + assert (p - 1) % q == 0 + # determine k + k = 0 + while f % q == 0: + k += 1 + f = f // q + # find z, x, r1 + f1 = igcdex(-f, q)[0] % q + z = f*f1 + x = (1 + z) // q + r1 = pow(s, x, p) + s1 = pow(s, f, p) + h = pow(g, f*q, p) + t = discrete_log(p, s1, h) + g2 = pow(g, z*t, p) + g3 = igcdex(g2, p)[0] + r = r1*g3 % p + #assert pow(r, q, p) == s + res = [r] + h = pow(g, (p - 1) // q, p) + #assert pow(h, q, p) == 1 + hx = r + for i in range(q - 1): + hx = (hx*h) % p + res.append(hx) + if all_roots: + res.sort() + return res + return min(res) + + + +def _help(m, prime_modulo_method, diff_method, expr_val): + """ + Helper function for _nthroot_mod_composite and polynomial_congruence. + + Parameters + ========== + + m : positive integer + prime_modulo_method : function to calculate the root of the congruence + equation for the prime divisors of m + diff_method : function to calculate derivative of expression at any + given point + expr_val : function to calculate value of the expression at any + given point + """ + from sympy.ntheory.modular import crt + f = factorint(m) + dd = {} + for p, e in f.items(): + tot_roots = set() + if e == 1: + tot_roots.update(prime_modulo_method(p)) + else: + for root in prime_modulo_method(p): + diff = diff_method(root, p) + if diff != 0: + ppow = p + m_inv = mod_inverse(diff, p) + for j in range(1, e): + ppow *= p + root = (root - expr_val(root, ppow) * m_inv) % ppow + tot_roots.add(root) + else: + new_base = p + roots_in_base = {root} + while new_base < pow(p, e): + new_base *= p + new_roots = set() + for k in roots_in_base: + if expr_val(k, new_base)!= 0: + continue + while k not in new_roots: + new_roots.add(k) + k = (k + (new_base // p)) % new_base + roots_in_base = new_roots + tot_roots = tot_roots | roots_in_base + if tot_roots == set(): + return [] + dd[pow(p, e)] = tot_roots + a = [] + m = [] + for x, y in dd.items(): + m.append(x) + a.append(list(y)) + return sorted({crt(m, list(i))[0] for i in product(*a)}) + + +def _nthroot_mod_composite(a, n, m): + """ + Find the solutions to ``x**n = a mod m`` when m is not prime. + """ + return _help(m, + lambda p: nthroot_mod(a, n, p, True), + lambda root, p: (pow(root, n - 1, p) * (n % p)) % p, + lambda root, p: (pow(root, n, p) - a) % p) + + +def nthroot_mod(a, n, p, all_roots=False): + """ + Find the solutions to ``x**n = a mod p``. + + Parameters + ========== + + a : integer + n : positive integer + p : positive integer + all_roots : if False returns the smallest root, else the list of roots + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import nthroot_mod + >>> nthroot_mod(11, 4, 19) + 8 + >>> nthroot_mod(11, 4, 19, True) + [8, 11] + >>> nthroot_mod(68, 3, 109) + 23 + """ + a = a % p + a, n, p = as_int(a), as_int(n), as_int(p) + + if n == 2: + return sqrt_mod(a, p, all_roots) + # see Hackman "Elementary Number Theory" (2009), page 76 + if not isprime(p): + return _nthroot_mod_composite(a, n, p) + if a % p == 0: + return [0] + if not is_nthpow_residue(a, n, p): + return [] if all_roots else None + if (p - 1) % n == 0: + return _nthroot_mod1(a, n, p, all_roots) + # The roots of ``x**n - a = 0 (mod p)`` are roots of + # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)`` + pa = n + pb = p - 1 + b = 1 + if pa < pb: + a, pa, b, pb = b, pb, a, pa + while pb: + # x**pa - a = 0; x**pb - b = 0 + # x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a = + # b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p + q, r = divmod(pa, pb) + c = pow(b, q, p) + c = igcdex(c, p)[0] + c = (c * a) % p + pa, pb = pb, r + a, b = b, c + if pa == 1: + if all_roots: + res = [a] + else: + res = a + elif pa == 2: + return sqrt_mod(a, p, all_roots) + else: + res = _nthroot_mod1(a, pa, p, all_roots) + return res + + +def quadratic_residues(p) -> list[int]: + """ + Returns the list of quadratic residues. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import quadratic_residues + >>> quadratic_residues(7) + [0, 1, 2, 4] + """ + p = as_int(p) + r = {pow(i, 2, p) for i in range(p // 2 + 1)} + return sorted(r) + + +def legendre_symbol(a, p): + r""" + Returns the Legendre symbol `(a / p)`. + + For an integer ``a`` and an odd prime ``p``, the Legendre symbol is + defined as + + .. math :: + \genfrac(){}{}{a}{p} = \begin{cases} + 0 & \text{if } p \text{ divides } a\\ + 1 & \text{if } a \text{ is a quadratic residue modulo } p\\ + -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p + \end{cases} + + Parameters + ========== + + a : integer + p : odd prime + + Examples + ======== + + >>> from sympy.ntheory import legendre_symbol + >>> [legendre_symbol(i, 7) for i in range(7)] + [0, 1, 1, -1, 1, -1, -1] + >>> sorted(set([i**2 % 7 for i in range(7)])) + [0, 1, 2, 4] + + See Also + ======== + + is_quad_residue, jacobi_symbol + + """ + a, p = as_int(a), as_int(p) + if not isprime(p) or p == 2: + raise ValueError("p should be an odd prime") + a = a % p + if not a: + return 0 + if pow(a, (p - 1) // 2, p) == 1: + return 1 + return -1 + + +def jacobi_symbol(m, n): + r""" + Returns the Jacobi symbol `(m / n)`. + + For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol + is defined as the product of the Legendre symbols corresponding to the + prime factors of ``n``: + + .. math :: + \genfrac(){}{}{m}{n} = + \genfrac(){}{}{m}{p^{1}}^{\alpha_1} + \genfrac(){}{}{m}{p^{2}}^{\alpha_2} + ... + \genfrac(){}{}{m}{p^{k}}^{\alpha_k} + \text{ where } n = + p_1^{\alpha_1} + p_2^{\alpha_2} + ... + p_k^{\alpha_k} + + Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1` + then ``m`` is a quadratic nonresidue modulo ``n``. + + But, unlike the Legendre symbol, if the Jacobi symbol + `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue + modulo ``n``. + + Parameters + ========== + + m : integer + n : odd positive integer + + Examples + ======== + + >>> from sympy.ntheory import jacobi_symbol, legendre_symbol + >>> from sympy import S + >>> jacobi_symbol(45, 77) + -1 + >>> jacobi_symbol(60, 121) + 1 + + The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can + be demonstrated as follows: + + >>> L = legendre_symbol + >>> S(45).factors() + {3: 2, 5: 1} + >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1 + True + + See Also + ======== + + is_quad_residue, legendre_symbol + """ + m, n = as_int(m), as_int(n) + if n < 0 or not n % 2: + raise ValueError("n should be an odd positive integer") + if m < 0 or m > n: + m %= n + if not m: + return int(n == 1) + if n == 1 or m == 1: + return 1 + if igcd(m, n) != 1: + return 0 + + j = 1 + while m != 0: + while m % 2 == 0 and m > 0: + m >>= 1 + if n % 8 in [3, 5]: + j = -j + m, n = n, m + if m % 4 == n % 4 == 3: + j = -j + m %= n + return j + + +class mobius(Function): + """ + Mobius function maps natural number to {-1, 0, 1} + + It is defined as follows: + 1) `1` if `n = 1`. + 2) `0` if `n` has a squared prime factor. + 3) `(-1)^k` if `n` is a square-free positive integer with `k` + number of prime factors. + + It is an important multiplicative function in number theory + and combinatorics. It has applications in mathematical series, + algebraic number theory and also physics (Fermion operator has very + concrete realization with Mobius Function model). + + Parameters + ========== + + n : positive integer + + Examples + ======== + + >>> from sympy.ntheory import mobius + >>> mobius(13*7) + 1 + >>> mobius(1) + 1 + >>> mobius(13*7*5) + -1 + >>> mobius(13**2) + 0 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function + .. [2] Thomas Koshy "Elementary Number Theory with Applications" + + """ + @classmethod + def eval(cls, n): + if n.is_integer: + if n.is_positive is not True: + raise ValueError("n should be a positive integer") + else: + raise TypeError("n should be an integer") + if n.is_prime: + return S.NegativeOne + elif n is S.One: + return S.One + elif n.is_Integer: + a = factorint(n) + if any(i > 1 for i in a.values()): + return S.Zero + return S.NegativeOne**len(a) + + +def _discrete_log_trial_mul(n, a, b, order=None): + """ + Trial multiplication algorithm for computing the discrete logarithm of + ``a`` to the base ``b`` modulo ``n``. + + The algorithm finds the discrete logarithm using exhaustive search. This + naive method is used as fallback algorithm of ``discrete_log`` when the + group order is very small. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul + >>> _discrete_log_trial_mul(41, 15, 7) + 3 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + if order is None: + order = n + x = 1 + for i in range(order): + if x == a: + return i + x = x * b % n + raise ValueError("Log does not exist") + + +def _discrete_log_shanks_steps(n, a, b, order=None): + """ + Baby-step giant-step algorithm for computing the discrete logarithm of + ``a`` to the base ``b`` modulo ``n``. + + The algorithm is a time-memory trade-off of the method of exhaustive + search. It uses `O(sqrt(m))` memory, where `m` is the group order. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps + >>> _discrete_log_shanks_steps(41, 15, 7) + 3 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + if order is None: + order = n_order(b, n) + m = isqrt(order) + 1 + T = {} + x = 1 + for i in range(m): + T[x] = i + x = x * b % n + z = mod_inverse(b, n) + z = pow(z, m, n) + x = a + for i in range(m): + if x in T: + return i * m + T[x] + x = x * z % n + raise ValueError("Log does not exist") + + +def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None): + """ + Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to + the base ``b`` modulo ``n``. + + It is a randomized algorithm with the same expected running time as + ``_discrete_log_shanks_steps``, but requires a negligible amount of memory. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho + >>> _discrete_log_pollard_rho(227, 3**7, 3) + 7 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + a %= n + b %= n + + if order is None: + order = n_order(b, n) + randint = _randint(rseed) + + for i in range(retries): + aa = randint(1, order - 1) + ba = randint(1, order - 1) + xa = pow(b, aa, n) * pow(a, ba, n) % n + + c = xa % 3 + if c == 0: + xb = a * xa % n + ab = aa + bb = (ba + 1) % order + elif c == 1: + xb = xa * xa % n + ab = (aa + aa) % order + bb = (ba + ba) % order + else: + xb = b * xa % n + ab = (aa + 1) % order + bb = ba + + for j in range(order): + c = xa % 3 + if c == 0: + xa = a * xa % n + ba = (ba + 1) % order + elif c == 1: + xa = xa * xa % n + aa = (aa + aa) % order + ba = (ba + ba) % order + else: + xa = b * xa % n + aa = (aa + 1) % order + + c = xb % 3 + if c == 0: + xb = a * xb % n + bb = (bb + 1) % order + elif c == 1: + xb = xb * xb % n + ab = (ab + ab) % order + bb = (bb + bb) % order + else: + xb = b * xb % n + ab = (ab + 1) % order + + c = xb % 3 + if c == 0: + xb = a * xb % n + bb = (bb + 1) % order + elif c == 1: + xb = xb * xb % n + ab = (ab + ab) % order + bb = (bb + bb) % order + else: + xb = b * xb % n + ab = (ab + 1) % order + + if xa == xb: + r = (ba - bb) % order + try: + e = mod_inverse(r, order) * (ab - aa) % order + if (pow(b, e, n) - a) % n == 0: + return e + except ValueError: + pass + break + raise ValueError("Pollard's Rho failed to find logarithm") + + +def _discrete_log_pohlig_hellman(n, a, b, order=None): + """ + Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to + the base ``b`` modulo ``n``. + + In order to compute the discrete logarithm, the algorithm takes advantage + of the factorization of the group order. It is more efficient when the + group order factors into many small primes. + + Examples + ======== + + >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman + >>> _discrete_log_pohlig_hellman(251, 210, 71) + 197 + + See Also + ======== + + discrete_log + + References + ========== + + .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + """ + from .modular import crt + a %= n + b %= n + + if order is None: + order = n_order(b, n) + + f = factorint(order) + l = [0] * len(f) + + for i, (pi, ri) in enumerate(f.items()): + for j in range(ri): + gj = pow(b, l[i], n) + aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n) + bj = pow(b, order // pi, n) + cj = discrete_log(n, aj, bj, pi, True) + l[i] += cj * pi**j + + d, _ = crt([pi**ri for pi, ri in f.items()], l) + return d + + +def discrete_log(n, a, b, order=None, prime_order=None): + """ + Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. + + This is a recursive function to reduce the discrete logarithm problem in + cyclic groups of composite order to the problem in cyclic groups of prime + order. + + It employs different algorithms depending on the problem (subgroup order + size, prime order or not): + + * Trial multiplication + * Baby-step giant-step + * Pollard's Rho + * Pohlig-Hellman + + Examples + ======== + + >>> from sympy.ntheory import discrete_log + >>> discrete_log(41, 15, 7) + 3 + + References + ========== + + .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html + .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & + Vanstone, S. A. (1997). + + """ + n, a, b = as_int(n), as_int(a), as_int(b) + if order is None: + order = n_order(b, n) + + if prime_order is None: + prime_order = isprime(order) + + if order < 1000: + return _discrete_log_trial_mul(n, a, b, order) + elif prime_order: + if order < 1000000000000: + return _discrete_log_shanks_steps(n, a, b, order) + return _discrete_log_pollard_rho(n, a, b, order) + + return _discrete_log_pohlig_hellman(n, a, b, order) + + + +def quadratic_congruence(a, b, c, p): + """ + Find the solutions to ``a x**2 + b x + c = 0 mod p. + + Parameters + ========== + + a : int + b : int + c : int + p : int + A positive integer. + """ + a = as_int(a) + b = as_int(b) + c = as_int(c) + p = as_int(p) + a = a % p + b = b % p + c = c % p + + if a == 0: + return linear_congruence(b, -c, p) + if p == 2: + roots = [] + if c % 2 == 0: + roots.append(0) + if (a + b + c) % 2 == 0: + roots.append(1) + return roots + if isprime(p): + inv_a = mod_inverse(a, p) + b *= inv_a + c *= inv_a + if b % 2 == 1: + b = b + p + d = ((b * b) // 4 - c) % p + y = sqrt_mod(d, p, all_roots=True) + res = set() + for i in y: + res.add((i - b // 2) % p) + return sorted(res) + y = sqrt_mod(b * b - 4 * a * c, 4 * a * p, all_roots=True) + res = set() + for i in y: + root = linear_congruence(2 * a, i - b, 4 * a * p) + for j in root: + res.add(j % p) + return sorted(res) + + +def _polynomial_congruence_prime(coefficients, p): + """A helper function used by polynomial_congruence. + It returns the root of a polynomial modulo prime number + by naive search from [0, p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + """ + + roots = [] + rank = len(coefficients) + for i in range(0, p): + f_val = 0 + for coeff in range(0,rank - 1): + f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p + f_val = f_val + coefficients[-1] + if f_val % p == 0: + roots.append(i) + return roots + + +def _diff_poly(root, coefficients, p): + """A helper function used by polynomial_congruence. + It returns the derivative of the polynomial evaluated at the + root (mod p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + root : integer + """ + + diff = 0 + rank = len(coefficients) + for coeff in range(0, rank - 1): + if not coefficients[coeff]: + continue + diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)* + coefficients[coeff]) % p + return diff % p + + +def _val_poly(root, coefficients, p): + """A helper function used by polynomial_congruence. + It returns value of the polynomial at root (mod p). + + Parameters + ========== + + coefficients : list of integers + p : prime number + root : integer + """ + rank = len(coefficients) + f_val = 0 + for coeff in range(0, rank - 1): + f_val = (f_val + pow(root, rank - coeff - 1, p)* + coefficients[coeff]) % p + f_val = f_val + coefficients[-1] + return f_val % p + + +def _valid_expr(expr): + """ + return coefficients of expr if it is a univariate polynomial + with integer coefficients else raise a ValueError. + """ + + if not expr.is_polynomial(): + raise ValueError("The expression should be a polynomial") + polynomial = Poly(expr) + if not polynomial.is_univariate: + raise ValueError("The expression should be univariate") + if not polynomial.domain == ZZ: + raise ValueError("The expression should should have integer coefficients") + return polynomial.all_coeffs() + + +def polynomial_congruence(expr, m): + """ + Find the solutions to a polynomial congruence equation modulo m. + + Parameters + ========== + + coefficients : Coefficients of the Polynomial + m : positive integer + + Examples + ======== + + >>> from sympy.ntheory import polynomial_congruence + >>> from sympy.abc import x + >>> expr = x**6 - 2*x**5 -35 + >>> polynomial_congruence(expr, 6125) + [3257] + """ + coefficients = _valid_expr(expr) + coefficients = [num % m for num in coefficients] + rank = len(coefficients) + if rank == 3: + return quadratic_congruence(*coefficients, m) + if rank == 2: + return quadratic_congruence(0, *coefficients, m) + if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients): + return nthroot_mod(-coefficients[-1], rank - 1, m, True) + if isprime(m): + return _polynomial_congruence_prime(coefficients, m) + return _help(m, + lambda p: _polynomial_congruence_prime(coefficients, p), + lambda root, p: _diff_poly(root, coefficients, p), + lambda root, p: _val_poly(root, coefficients, p)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..babab948f121ea343b96a61f78386210bcac6b16 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py @@ -0,0 +1,73 @@ +from sympy.core import GoldenRatio as phi +from sympy.core.numbers import (Rational, pi) +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.ntheory.continued_fraction import \ + (continued_fraction_periodic as cf_p, + continued_fraction_iterator as cf_i, + continued_fraction_convergents as cf_c, + continued_fraction_reduce as cf_r, + continued_fraction as cf) +from sympy.testing.pytest import raises + + +def test_continued_fraction(): + assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1) + assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1) + t = sqrt(2) + assert cf((1 + t)*(1 - t)) == cf(-1) + for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5, + (2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]: + assert (cf_r(cf(n)) - n).expand() == 0 + assert (cf_r(cf(-n)) + n).expand() == 0 + raises(ValueError, lambda: cf(sqrt(2 + sqrt(3)))) + raises(ValueError, lambda: cf(sqrt(2) + sqrt(3))) + raises(ValueError, lambda: cf(pi)) + raises(ValueError, lambda: cf(.1)) + + raises(ValueError, lambda: cf_p(1, 0, 0)) + raises(ValueError, lambda: cf_p(1, 1, -1)) + assert cf_p(4, 3, 0) == [1, 3] + assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]] + assert cf_p(1, 1, 0) == [1] + assert cf_p(3, 4, 0) == [0, 1, 3] + assert cf_p(4, 5, 0) == [0, 1, 4] + assert cf_p(5, 6, 0) == [0, 1, 5] + assert cf_p(11, 13, 0) == [0, 1, 5, 2] + assert cf_p(16, 19, 0) == [0, 1, 5, 3] + assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2] + assert cf_p(1, 2, 5) == [[1]] + assert cf_p(0, 1, 2) == [1, [2]] + assert cf_p(6, 7, 49) == [1, 1, 6] + assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4] + assert cf_p(3245, 10000) == [0, 3, 12, 4, 13] + assert cf_p(1932, 2568) == [0, 1, 3, 26, 2] + assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23] + + def take(iterator, n=7): + res = [] + for i, t in enumerate(cf_i(iterator)): + if i >= n: + break + res.append(t) + return res + + assert take(phi) == [1, 1, 1, 1, 1, 1, 1] + assert take(pi) == [3, 7, 15, 1, 292, 1, 1] + + assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2] + assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2] + + assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)] + assert list(cf_c([2])) == [S(2)] + assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), + Rational(8, 5), Rational(13, 8), Rational(21, 13)] + assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)] + + assert cf_r([1, 6, 1, 8]) == Rational(71, 62) + assert cf_r([3]) == S(3) + assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29) + assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0 + assert cf_r([1, 5, 9]) == Rational(55, 46) + assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0 + assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py new file mode 100644 index 0000000000000000000000000000000000000000..6e58ff31aec7609407a8d90afd0bbdacebb66935 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py @@ -0,0 +1,34 @@ +from sympy.ntheory import count_digits, digits, is_palindromic + +from sympy.testing.pytest import raises + + +def test_digits(): + assert all([digits(n, 2)[1:] == [int(d) for d in format(n, 'b')] + for n in range(20)]) + assert all([digits(n, 8)[1:] == [int(d) for d in format(n, 'o')] + for n in range(20)]) + assert all([digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')] + for n in range(20)]) + assert digits(2345, 34) == [34, 2, 0, 33] + assert digits(384753, 71) == [71, 1, 5, 23, 4] + assert digits(93409, 10) == [10, 9, 3, 4, 0, 9] + assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9] + assert digits(35, 10) == [10, 3, 5] + assert digits(35, 10, 3) == [10, 0, 3, 5] + assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5] + raises(ValueError, lambda: digits(2, 2, 1)) + + +def test_count_digits(): + assert count_digits(55, 2) == {1: 5, 0: 1} + assert count_digits(55, 10) == {5: 2} + n = count_digits(123) + assert n[4] == 0 and type(n[4]) is int + + +def test_is_palindromic(): + assert is_palindromic(-11) + assert is_palindromic(11) + assert is_palindromic(0o121, 8) + assert not is_palindromic(123) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dbffee209539d9f81981f89c77337b583fa42b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py @@ -0,0 +1,63 @@ +from sympy.ntheory.ecm import ecm, Point +from sympy.testing.pytest import slow + +@slow +def test_ecm(): + assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297} + assert ecm(46167045131415113) == {43, 2634823, 407485517} + assert ecm(631211032315670776841) == {9312934919, 67777885039} + assert ecm(398883434337287) == {99476569, 4009823} + assert ecm(64211816600515193) == {281719, 359641, 633767} + assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123} + assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571} + assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803} + assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721} + #This takes ~10secs while factorint is not able to factorize this even in ~10mins + assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809} + + +def test_Point(): + from sympy.core.numbers import mod_inverse + #The curve is of the form y**2 = x**3 + a*x**2 + x + mod = 101 + a = 10 + a_24 = (a + 2)*mod_inverse(4, mod) + p1 = Point(10, 17, a_24, mod) + p2 = p1.double() + assert p2 == Point(68, 56, a_24, mod) + p4 = p2.double() + assert p4 == Point(22, 64, a_24, mod) + p8 = p4.double() + assert p8 == Point(71, 95, a_24, mod) + p16 = p8.double() + assert p16 == Point(5, 16, a_24, mod) + p32 = p16.double() + assert p32 == Point(33, 96, a_24, mod) + + # p3 = p2 + p1 + p3 = p2.add(p1, p1) + assert p3 == Point(1, 61, a_24, mod) + # p5 = p3 + p2 or p4 + p1 + p5 = p3.add(p2, p1) + assert p5 == Point(49, 90, a_24, mod) + assert p5 == p4.add(p1, p3) + # p6 = 2*p3 + p6 = p3.double() + assert p6 == Point(87, 43, a_24, mod) + assert p6 == p4.add(p2, p2) + # p7 = p5 + p2 + p7 = p5.add(p2, p3) + assert p7 == Point(69, 23, a_24, mod) + assert p7 == p4.add(p3, p1) + assert p7 == p6.add(p1, p5) + # p9 = p5 + p4 + p9 = p5.add(p4, p1) + assert p9 == Point(56, 99, a_24, mod) + assert p9 == p6.add(p3, p3) + assert p9 == p7.add(p2, p5) + assert p9 == p8.add(p1, p7) + + assert p5 == p1.mont_ladder(5) + assert p9 == p1.mont_ladder(9) + assert p16 == p1.mont_ladder(16) + assert p9 == p3.mont_ladder(3) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a9fac578d93a88a648bdcf8dc34550cf4a7573 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py @@ -0,0 +1,49 @@ +from sympy.core.numbers import Rational +from sympy.ntheory.egyptian_fraction import egyptian_fraction +from sympy.core.add import Add +from sympy.testing.pytest import raises +from sympy.core.random import random_complex_number + + +def test_egyptian_fraction(): + def test_equality(r, alg="Greedy"): + return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)]) + + r = random_complex_number(a=0, c=1, b=0, d=0, rational=True) + assert test_equality(r) + + assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345] + assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26] + assert egyptian_fraction(Rational(23, 101), "Greedy") == \ + [5, 37, 1438, 2985448, 40108045937720] + assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \ + [2, 6, 12, 35, 276, 2415] + assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \ + [6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807, + 1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443, + 3267056, 3581556, 10192056, 10650056950806] + assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30] + assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737] + raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9))) + assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7, + 14, 574, 2788, 6460, + 11590, 33062, 113820] + assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 27, 744, 893588, + 1251493536607, + 20361068938197002344405230] + + +def test_input(): + r = (2,3), Rational(2, 3), (Rational(2), Rational(3)) + for m in ["Greedy", "Graham Jewett", "Takenouchi", "Golomb"]: + for i in r: + d = egyptian_fraction(i, m) + assert all(i.is_Integer for i in d) + if m == "Graham Jewett": + assert d == [3, 4, 12] + else: + assert d == [2, 6] + # check prefix + d = egyptian_fraction(Rational(5, 3)) + assert d == [1, 2, 6] and all(i.is_Integer for i in d) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py new file mode 100644 index 0000000000000000000000000000000000000000..626dde0dec87d45d83a635eda3af441e3a635e66 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py @@ -0,0 +1,685 @@ +from sympy.concrete.summations import summation +from sympy.core.containers import Dict +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.combinatorial.factorials import factorial as fac +from sympy.core.evalf import bitcount +from sympy.core.numbers import Integer, Rational + +from sympy.ntheory import (totient, + factorint, primefactors, divisors, nextprime, + primerange, pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial, + trailing, divisor_count, primorial, pollard_pm1, divisor_sigma, + factorrat, reduced_totient) +from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors, + antidivisors, antidivisor_count, core, udivisors, udivisor_sigma, + udivisor_count, proper_divisor_count, primenu, primeomega, small_trailing, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, dra, drm) + +from sympy.testing.pytest import raises, slow + +from sympy.utilities.iterables import capture + + +def fac_multiplicity(n, p): + """Return the power of the prime number p in the + factorization of n!""" + if p > n: + return 0 + if p > n//2: + return 1 + q, m = n, 0 + while q >= p: + q //= p + m += q + return m + + +def multiproduct(seq=(), start=1): + """ + Return the product of a sequence of factors with multiplicities, + times the value of the parameter ``start``. The input may be a + sequence of (factor, exponent) pairs or a dict of such pairs. + + >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 + 279936 + + """ + if not seq: + return start + if isinstance(seq, dict): + seq = iter(seq.items()) + units = start + multi = [] + for base, exp in seq: + if not exp: + continue + elif exp == 1: + units *= base + else: + if exp % 2: + units *= base + multi.append((base, exp//2)) + return units * multiproduct(multi)**2 + + +def test_trailing_bitcount(): + assert trailing(0) == 0 + assert trailing(1) == 0 + assert trailing(-1) == 0 + assert trailing(2) == 1 + assert trailing(7) == 0 + assert trailing(-7) == 0 + for i in range(100): + assert trailing(1 << i) == i + assert trailing((1 << i) * 31337) == i + assert trailing(1 << 1000001) == 1000001 + assert trailing((1 << 273956)*7**37) == 273956 + # issue 12709 + big = small_trailing[-1]*2 + assert trailing(-big) == trailing(big) + assert bitcount(-big) == bitcount(big) + + +def test_multiplicity(): + for b in range(2, 20): + for i in range(100): + assert multiplicity(b, b**i) == i + assert multiplicity(b, (b**i) * 23) == i + assert multiplicity(b, (b**i) * 1000249) == i + # Should be fast + assert multiplicity(10, 10**10023) == 10023 + # Should exit quickly + assert multiplicity(10**10, 10**10) == 1 + # Should raise errors for bad input + raises(ValueError, lambda: multiplicity(1, 1)) + raises(ValueError, lambda: multiplicity(1, 2)) + raises(ValueError, lambda: multiplicity(1.3, 2)) + raises(ValueError, lambda: multiplicity(2, 0)) + raises(ValueError, lambda: multiplicity(1.3, 0)) + + # handles Rationals + assert multiplicity(10, Rational(30, 7)) == 1 + assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1 + assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2 + assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1 + assert multiplicity(3, Rational(1, 9)) == -2 + + +def test_multiplicity_in_factorial(): + n = fac(1000) + for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96): + assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000) + + +def test_perfect_power(): + raises(ValueError, lambda: perfect_power(0.1)) + assert perfect_power(0) is False + assert perfect_power(1) is False + assert perfect_power(2) is False + assert perfect_power(3) is False + assert perfect_power(4) == (2, 2) + assert perfect_power(14) is False + assert perfect_power(25) == (5, 2) + assert perfect_power(22) is False + assert perfect_power(22, [2]) is False + assert perfect_power(137**(3*5*13)) == (137, 3*5*13) + assert perfect_power(137**(3*5*13) + 1) is False + assert perfect_power(137**(3*5*13) - 1) is False + assert perfect_power(103005006004**7) == (103005006004, 7) + assert perfect_power(103005006004**7 + 1) is False + assert perfect_power(103005006004**7 - 1) is False + assert perfect_power(103005006004**12) == (103005006004, 12) + assert perfect_power(103005006004**12 + 1) is False + assert perfect_power(103005006004**12 - 1) is False + assert perfect_power(2**10007) == (2, 10007) + assert perfect_power(2**10007 + 1) is False + assert perfect_power(2**10007 - 1) is False + assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60) + assert perfect_power((9**99 + 1)**60 + 1) is False + assert perfect_power((9**99 + 1)**60 - 1) is False + assert perfect_power((10**40000)**2, big=False) == (10**40000, 2) + assert perfect_power(10**100000) == (10, 100000) + assert perfect_power(10**100001) == (10, 100001) + assert perfect_power(13**4, [3, 5]) is False + assert perfect_power(3**4, [3, 10], factor=0) is False + assert perfect_power(3**3*5**3) == (15, 3) + assert perfect_power(2**3*5**5) is False + assert perfect_power(2*13**4) is False + assert perfect_power(2**5*3**3) is False + t = 2**24 + for d in divisors(24): + m = perfect_power(t*3**d) + assert m and m[1] == d or d == 1 + m = perfect_power(t*3**d, big=False) + assert m and m[1] == 2 or d == 1 or d == 3, (d, m) + + # negatives and non-integer rationals + assert perfect_power(-4) is False + assert perfect_power(-8) == (-2, 3) + assert perfect_power(Rational(1, 2)**3) == (S.Half, 3) + assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3) + + +@slow +def test_factorint(): + assert primefactors(123456) == [2, 3, 643] + assert factorint(0) == {0: 1} + assert factorint(1) == {} + assert factorint(-1) == {-1: 1} + assert factorint(-2) == {-1: 1, 2: 1} + assert factorint(-16) == {-1: 1, 2: 4} + assert factorint(2) == {2: 1} + assert factorint(126) == {2: 1, 3: 2, 7: 1} + assert factorint(123456) == {2: 6, 3: 1, 643: 1} + assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1} + assert factorint(64015937) == {7993: 1, 8009: 1} + assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1} + #issue 19683 + assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1} + #issue 17676 + assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1} + assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1} + assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1} + + assert factorint(0, multiple=True) == [0] + assert factorint(1, multiple=True) == [] + assert factorint(-1, multiple=True) == [-1] + assert factorint(-2, multiple=True) == [-1, 2] + assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2] + assert factorint(2, multiple=True) == [2] + assert factorint(24, multiple=True) == [2, 2, 2, 3] + assert factorint(126, multiple=True) == [2, 3, 3, 7] + assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643] + assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337] + assert factorint(64015937, multiple=True) == [7993, 8009] + assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721] + + assert factorint(fac(1, evaluate=False)) == {} + assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1} + assert factorint(fac(15, evaluate=False)) == \ + {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1} + assert factorint(fac(20, evaluate=False)) == \ + {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1} + assert factorint(fac(23, evaluate=False)) == \ + {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1} + + assert multiproduct(factorint(fac(200))) == fac(200) + assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200) + for b, e in factorint(fac(150)).items(): + assert e == fac_multiplicity(150, b) + for b, e in factorint(fac(150, evaluate=False)).items(): + assert e == fac_multiplicity(150, b) + assert factorint(103005006059**7) == {103005006059: 7} + assert factorint(31337**191) == {31337: 191} + assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \ + {2: 1000, 3: 500, 257: 127, 383: 60} + assert len(factorint(fac(10000))) == 1229 + assert len(factorint(fac(10000, evaluate=False))) == 1229 + assert factorint(12932983746293756928584532764589230) == \ + {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1} + assert factorint(727719592270351) == {727719592270351: 1} + assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1) + for n in range(60000): + assert multiproduct(factorint(n)) == n + assert pollard_rho(2**64 + 1, seed=1) == 274177 + assert pollard_rho(19, seed=1) is None + assert factorint(3, limit=2) == {3: 1} + assert factorint(12345) == {3: 1, 5: 1, 823: 1} + assert factorint( + 12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit + assert factorint(1, limit=1) == {} + assert factorint(0, 3) == {0: 1} + assert factorint(12, limit=1) == {12: 1} + assert factorint(30, limit=2) == {2: 1, 15: 1} + assert factorint(16, limit=2) == {2: 4} + assert factorint(124, limit=3) == {2: 2, 31: 1} + assert factorint(4*31**2, limit=3) == {2: 2, 31: 2} + p1 = nextprime(2**32) + p2 = nextprime(2**16) + p3 = nextprime(p2) + assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1} + assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1} + assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1} + assert factorint(primorial(17) + 1, use_pm1=0) == \ + {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1} + # when prime b is closer than approx sqrt(8*p) to prime p then they are + # "close" and have a trivial factorization + a = nextprime(2**2**8) # 78 digits + b = nextprime(a + 2**2**4) + assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1)) + + raises(ValueError, lambda: pollard_rho(4)) + raises(ValueError, lambda: pollard_pm1(3)) + raises(ValueError, lambda: pollard_pm1(10, B=2)) + # verbose coverage + n = nextprime(2**16)*nextprime(2**17)*nextprime(1901) + assert 'with primes' in capture(lambda: factorint(n, verbose=1)) + capture(lambda: factorint(nextprime(2**16)*1012, verbose=1)) + + n = nextprime(2**17) + capture(lambda: factorint(n**3, verbose=1)) # perfect power termination + capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg + + # exceed 1st + n = nextprime(2**17) + n *= nextprime(n) + assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1)) + n *= nextprime(n) + assert len(factorint(n)) == 3 + assert len(factorint(n, limit=p1)) == 3 + n *= nextprime(2*n) + # exceed 2nd + assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1)) + assert capture( + lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2 + # non-prime pm1 result + n = nextprime(8069) + n *= nextprime(2*n)*nextprime(2*n, 2) + capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result + # factor fermat composite + p1 = nextprime(2**17) + p2 = nextprime(2*p1) + assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6} + # Test for non integer input + raises(ValueError, lambda: factorint(4.5)) + # test dict/Dict input + sans = '2**10*3**3' + n = {4: 2, 12: 3} + assert str(factorint(n)) == sans + assert str(factorint(Dict(n))) == sans + + +def test_divisors_and_divisor_count(): + assert divisors(-1) == [1] + assert divisors(0) == [] + assert divisors(1) == [1] + assert divisors(2) == [1, 2] + assert divisors(3) == [1, 3] + assert divisors(17) == [1, 17] + assert divisors(10) == [1, 2, 5, 10] + assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100] + assert divisors(101) == [1, 101] + + assert divisor_count(0) == 0 + assert divisor_count(-1) == 1 + assert divisor_count(1) == 1 + assert divisor_count(6) == 4 + assert divisor_count(12) == 6 + + assert divisor_count(180, 3) == divisor_count(180//3) + assert divisor_count(2*3*5, 7) == 0 + + +def test_proper_divisors_and_proper_divisor_count(): + assert proper_divisors(-1) == [] + assert proper_divisors(0) == [] + assert proper_divisors(1) == [] + assert proper_divisors(2) == [1] + assert proper_divisors(3) == [1] + assert proper_divisors(17) == [1] + assert proper_divisors(10) == [1, 2, 5] + assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50] + assert proper_divisors(1000000007) == [1] + + assert proper_divisor_count(0) == 0 + assert proper_divisor_count(-1) == 0 + assert proper_divisor_count(1) == 0 + assert proper_divisor_count(36) == 8 + assert proper_divisor_count(2*3*5) == 7 + + +def test_udivisors_and_udivisor_count(): + assert udivisors(-1) == [1] + assert udivisors(0) == [] + assert udivisors(1) == [1] + assert udivisors(2) == [1, 2] + assert udivisors(3) == [1, 3] + assert udivisors(17) == [1, 17] + assert udivisors(10) == [1, 2, 5, 10] + assert udivisors(100) == [1, 4, 25, 100] + assert udivisors(101) == [1, 101] + assert udivisors(1000) == [1, 8, 125, 1000] + + assert udivisor_count(0) == 0 + assert udivisor_count(-1) == 1 + assert udivisor_count(1) == 1 + assert udivisor_count(6) == 4 + assert udivisor_count(12) == 4 + + assert udivisor_count(180) == 8 + assert udivisor_count(2*3*5*7) == 16 + + +def test_issue_6981(): + S = set(divisors(4)).union(set(divisors(Integer(2)))) + assert S == {1,2,4} + + +def test_totient(): + assert [totient(k) for k in range(1, 12)] == \ + [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10] + assert totient(5005) == 2880 + assert totient(5006) == 2502 + assert totient(5009) == 5008 + assert totient(2**100) == 2**99 + + raises(ValueError, lambda: totient(30.1)) + raises(ValueError, lambda: totient(20.001)) + + m = Symbol("m", integer=True) + assert totient(m) + assert totient(m).subs(m, 3**10) == 3**10 - 3**9 + assert summation(totient(m), (m, 1, 11)) == 42 + + n = Symbol("n", integer=True, positive=True) + assert totient(n).is_integer + + x=Symbol("x", integer=False) + raises(ValueError, lambda: totient(x)) + + y=Symbol("y", positive=False) + raises(ValueError, lambda: totient(y)) + + z=Symbol("z", positive=True, integer=True) + raises(ValueError, lambda: totient(2**(-z))) + + +def test_reduced_totient(): + assert [reduced_totient(k) for k in range(1, 16)] == \ + [1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4] + assert reduced_totient(5005) == 60 + assert reduced_totient(5006) == 2502 + assert reduced_totient(5009) == 5008 + assert reduced_totient(2**100) == 2**98 + + m = Symbol("m", integer=True) + assert reduced_totient(m) + assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9 + assert summation(reduced_totient(m), (m, 1, 16)) == 68 + + n = Symbol("n", integer=True, positive=True) + assert reduced_totient(n).is_integer + + +def test_divisor_sigma(): + assert [divisor_sigma(k) for k in range(1, 12)] == \ + [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12] + assert [divisor_sigma(k, 2) for k in range(1, 12)] == \ + [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122] + assert divisor_sigma(23450) == 50592 + assert divisor_sigma(23450, 0) == 24 + assert divisor_sigma(23450, 1) == 50592 + assert divisor_sigma(23450, 2) == 730747500 + assert divisor_sigma(23450, 3) == 14666785333344 + + a = Symbol("a", prime=True) + b = Symbol("b", prime=True) + j = Symbol("j", integer=True, positive=True) + k = Symbol("k", integer=True, positive=True) + assert divisor_sigma(a**j*b**k) == (a**(j + 1) - 1)*(b**(k + 1) - 1)/((a - 1)*(b - 1)) + assert divisor_sigma(a**j*b**k, 2) == (a**(2*j + 2) - 1)*(b**(2*k + 2) - 1)/((a**2 - 1)*(b**2 - 1)) + assert divisor_sigma(a**j*b**k, 0) == (j + 1)*(k + 1) + + m = Symbol("m", integer=True) + k = Symbol("k", integer=True) + assert divisor_sigma(m) + assert divisor_sigma(m, k) + assert divisor_sigma(m).subs(m, 3**10) == 88573 + assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597 + assert summation(divisor_sigma(m), (m, 1, 11)) == 99 + + +def test_udivisor_sigma(): + assert [udivisor_sigma(k) for k in range(1, 12)] == \ + [1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12] + assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \ + [1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332] + assert udivisor_sigma(23450) == 42432 + assert udivisor_sigma(23450, 0) == 16 + assert udivisor_sigma(23450, 1) == 42432 + assert udivisor_sigma(23450, 2) == 702685000 + assert udivisor_sigma(23450, 4) == 321426961814978248 + + m = Symbol("m", integer=True) + k = Symbol("k", integer=True) + assert udivisor_sigma(m) + assert udivisor_sigma(m, k) + assert udivisor_sigma(m).subs(m, 4**9) == 262145 + assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737 + assert summation(udivisor_sigma(m), (m, 2, 15)) == 169 + + +def test_issue_4356(): + assert factorint(1030903) == {53: 2, 367: 1} + + +def test_divisors(): + assert divisors(28) == [1, 2, 4, 7, 14, 28] + assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105] + assert divisors(0) == [] + + +def test_divisor_count(): + assert divisor_count(0) == 0 + assert divisor_count(6) == 4 + + +def test_proper_divisors(): + assert proper_divisors(-1) == [] + assert proper_divisors(28) == [1, 2, 4, 7, 14] + assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35] + + +def test_proper_divisor_count(): + assert proper_divisor_count(6) == 3 + assert proper_divisor_count(108) == 11 + + +def test_antidivisors(): + assert antidivisors(-1) == [] + assert antidivisors(-3) == [2] + assert antidivisors(14) == [3, 4, 9] + assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158] + assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230] + assert antidivisors(393216) == [262144] + assert sorted(x for x in antidivisors(3*5*7, 1)) == \ + [2, 6, 10, 11, 14, 19, 30, 42, 70] + assert antidivisors(1) == [] + + +def test_antidivisor_count(): + assert antidivisor_count(0) == 0 + assert antidivisor_count(-1) == 0 + assert antidivisor_count(-4) == 1 + assert antidivisor_count(20) == 3 + assert antidivisor_count(25) == 5 + assert antidivisor_count(38) == 7 + assert antidivisor_count(180) == 6 + assert antidivisor_count(2*3*5) == 3 + + +def test_smoothness_and_smoothness_p(): + assert smoothness(1) == (1, 1) + assert smoothness(2**4*3**2) == (3, 16) + + assert smoothness_p(10431, m=1) == \ + (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) + assert smoothness_p(10431) == \ + (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) + assert smoothness_p(10431, power=1) == \ + (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) + assert smoothness_p(21477639576571, visual=1) == \ + 'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \ + 'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931' + + +def test_visual_factorint(): + assert factorint(1, visual=1) == 1 + forty2 = factorint(42, visual=True) + assert type(forty2) == Mul + assert str(forty2) == '2**1*3**1*7**1' + assert factorint(1, visual=True) is S.One + no = {"evaluate": False} + assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no), + Pow(3, 2, **no), + Pow(7, 2, **no), **no) + assert -1 in factorint(-42, visual=True).args + + +def test_factorrat(): + assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1' + assert str(factorrat(Rational(1, 1), visual=True)) == '1' + assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)' + assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)' + assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)' + + assert factorrat(S(12)/1, multiple=True) == [2, 2, 3] + assert factorrat(Rational(1, 1), multiple=True) == [] + assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5] + assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5] + assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3] + assert factorrat(S(-25)/14/9, multiple=True) == \ + [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5] + + +def test_visual_io(): + sm = smoothness_p + fi = factorint + # with smoothness_p + n = 124 + d = fi(n) + m = fi(d, visual=True) + t = sm(n) + s = sm(t) + for th in [d, s, t, n, m]: + assert sm(th, visual=True) == s + assert sm(th, visual=1) == s + for th in [d, s, t, n, m]: + assert sm(th, visual=False) == t + assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t] + assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t] + + # with factorint + for th in [d, m, n]: + assert fi(th, visual=True) == m + assert fi(th, visual=1) == m + for th in [d, m, n]: + assert fi(th, visual=False) == d + assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d] + assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d] + + # test reevaluation + no = {"evaluate": False} + assert sm({4: 2}, visual=False) == sm(16) + assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), + visual=False) == sm(2**10) + + assert fi({4: 2}, visual=False) == fi(16) + assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), + visual=False) == fi(2**10) + + +def test_core(): + assert core(35**13, 10) == 42875 + assert core(210**2) == 1 + assert core(7776, 3) == 36 + assert core(10**27, 22) == 10**5 + assert core(537824) == 14 + assert core(1, 6) == 1 + + +def test_primenu(): + assert primenu(2) == 1 + assert primenu(2 * 3) == 2 + assert primenu(2 * 3 * 5) == 3 + assert primenu(3 * 25) == primenu(3) + primenu(25) + assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1] + assert primenu(fac(50)) == 15 + assert primenu(2 ** 9941 - 1) == 1 + n = Symbol('n', integer=True) + assert primenu(n) + assert primenu(n).subs(n, 2 ** 31 - 1) == 1 + assert summation(primenu(n), (n, 2, 30)) == 43 + + +def test_primeomega(): + assert primeomega(2) == 1 + assert primeomega(2 * 2) == 2 + assert primeomega(2 * 2 * 3) == 3 + assert primeomega(3 * 25) == primeomega(3) + primeomega(25) + assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1] + assert primeomega(fac(50)) == 108 + assert primeomega(2 ** 9941 - 1) == 1 + n = Symbol('n', integer=True) + assert primeomega(n) + assert primeomega(n).subs(n, 2 ** 31 - 1) == 1 + assert summation(primeomega(n), (n, 2, 30)) == 59 + + +def test_mersenne_prime_exponent(): + assert mersenne_prime_exponent(1) == 2 + assert mersenne_prime_exponent(4) == 7 + assert mersenne_prime_exponent(10) == 89 + assert mersenne_prime_exponent(25) == 21701 + raises(ValueError, lambda: mersenne_prime_exponent(52)) + raises(ValueError, lambda: mersenne_prime_exponent(0)) + + +def test_is_perfect(): + assert is_perfect(6) is True + assert is_perfect(15) is False + assert is_perfect(28) is True + assert is_perfect(400) is False + assert is_perfect(496) is True + assert is_perfect(8128) is True + assert is_perfect(10000) is False + + +def test_is_mersenne_prime(): + assert is_mersenne_prime(10) is False + assert is_mersenne_prime(127) is True + assert is_mersenne_prime(511) is False + assert is_mersenne_prime(131071) is True + assert is_mersenne_prime(2147483647) is True + + +def test_is_abundant(): + assert is_abundant(10) is False + assert is_abundant(12) is True + assert is_abundant(18) is True + assert is_abundant(21) is False + assert is_abundant(945) is True + + +def test_is_deficient(): + assert is_deficient(10) is True + assert is_deficient(22) is True + assert is_deficient(56) is False + assert is_deficient(20) is False + assert is_deficient(36) is False + + +def test_is_amicable(): + assert is_amicable(173, 129) is False + assert is_amicable(220, 284) is True + assert is_amicable(8756, 8756) is False + +def test_dra(): + assert dra(19, 12) == 8 + assert dra(2718, 10) == 9 + assert dra(0, 22) == 0 + assert dra(23456789, 10) == 8 + raises(ValueError, lambda: dra(24, -2)) + raises(ValueError, lambda: dra(24.2, 5)) + +def test_drm(): + assert drm(19, 12) == 7 + assert drm(2718, 10) == 2 + assert drm(0, 15) == 0 + assert drm(234161, 10) == 6 + raises(ValueError, lambda: drm(24, -2)) + raises(ValueError, lambda: drm(11.6, 9)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py new file mode 100644 index 0000000000000000000000000000000000000000..10ebb1d3d3bdf5f736a6229579ae4c42a805745e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py @@ -0,0 +1,34 @@ +from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence +from sympy.testing.pytest import raises + + +def test_crt(): + def mcrt(m, v, r, symmetric=False): + assert crt(m, v, symmetric)[0] == r + mm, e, s = crt1(m) + assert crt2(m, v, mm, e, s, symmetric) == (r, mm) + + mcrt([2, 3, 5], [0, 0, 0], 0) + mcrt([2, 3, 5], [1, 1, 1], 1) + + mcrt([2, 3, 5], [-1, -1, -1], -1, True) + mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False) + + assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800) + + +def test_modular(): + assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140) + assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None + assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547) + assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547) + assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None + assert solve_congruence( + *list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547) + assert solve_congruence( + *list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094) + assert solve_congruence( + *list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094) + assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None + raises( + ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17])))) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..b455c5cc979b9ba9756c9da88c1694471115cd5d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py @@ -0,0 +1,48 @@ +from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients) +from sympy.ntheory.multinomial import multinomial_coefficients_iterator + + +def test_binomial_coefficients_list(): + assert binomial_coefficients_list(0) == [1] + assert binomial_coefficients_list(1) == [1, 1] + assert binomial_coefficients_list(2) == [1, 2, 1] + assert binomial_coefficients_list(3) == [1, 3, 3, 1] + assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1] + assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1] + assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1] + + +def test_binomial_coefficients(): + for n in range(15): + c = binomial_coefficients(n) + l = [c[k] for k in sorted(c)] + assert l == binomial_coefficients_list(n) + + +def test_multinomial_coefficients(): + assert multinomial_coefficients(1, 1) == {(1,): 1} + assert multinomial_coefficients(1, 2) == {(2,): 1} + assert multinomial_coefficients(1, 3) == {(3,): 1} + assert multinomial_coefficients(2, 0) == {(0, 0): 1} + assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1} + assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2} + assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1, + (2, 1): 3} + assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1, + (0, 0, 1): 1} + assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1, + (1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1} + mc = multinomial_coefficients(3, 3) + assert mc == {(2, 1, 0): 3, (0, 3, 0): 1, + (1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1, + (2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1} + assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1} + assert dict( + multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1} + assert dict(multinomial_coefficients_iterator(2, 2)) == \ + {(2, 0): 1, (0, 2): 1, (1, 1): 2} + assert dict(multinomial_coefficients_iterator(3, 3)) == mc + it = multinomial_coefficients_iterator(7, 2) + assert [next(it) for i in range(4)] == \ + [((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2), + ((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..1a347899c2efc8ae2b8a417dbb422a83cd529c61 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py @@ -0,0 +1,12 @@ +from sympy.ntheory import npartitions + + +def test_partitions(): + assert [npartitions(k) for k in range(13)] == \ + [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77] + assert npartitions(100) == 190569292 + assert npartitions(200) == 3972999029388 + assert npartitions(1000) == 24061467864032622473692149727991 + assert npartitions(2000) == 4720819175619413888601432406799959512200344166 + assert npartitions(10000) % 10**10 == 6916435144 + assert npartitions(100000) % 10**10 == 9421098519 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py new file mode 100644 index 0000000000000000000000000000000000000000..06fff52d16acd9c79f86e0088ba7ad5d80a9cfc7 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py @@ -0,0 +1,286 @@ +from collections import defaultdict +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) + +from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \ + legendre_symbol, jacobi_symbol, totient, primerange, sqrt_mod, \ + primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \ + sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, \ + polynomial_congruence +from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \ + _discrete_log_trial_mul, _discrete_log_shanks_steps, \ + _discrete_log_pollard_rho, _discrete_log_pohlig_hellman +from sympy.polys.domains import ZZ +from sympy.testing.pytest import raises + + +def test_residue(): + assert n_order(2, 13) == 12 + assert [n_order(a, 7) for a in range(1, 7)] == \ + [1, 3, 6, 3, 6, 2] + assert n_order(5, 17) == 16 + assert n_order(17, 11) == n_order(6, 11) + assert n_order(101, 119) == 6 + assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650 + raises(ValueError, lambda: n_order(6, 9)) + + assert is_primitive_root(2, 7) is False + assert is_primitive_root(3, 8) is False + assert is_primitive_root(11, 14) is False + assert is_primitive_root(12, 17) == is_primitive_root(29, 17) + raises(ValueError, lambda: is_primitive_root(3, 6)) + + for p in primerange(3, 100): + it = _primitive_root_prime_iter(p) + assert len(list(it)) == totient(totient(p)) + assert primitive_root(97) == 5 + assert primitive_root(97**2) == 5 + assert primitive_root(40487) == 5 + # note that primitive_root(40487) + 40487 = 40492 is a primitive root + # of 40487**2, but it is not the smallest + assert primitive_root(40487**2) == 10 + assert primitive_root(82) == 7 + p = 10**50 + 151 + assert primitive_root(p) == 11 + assert primitive_root(2*p) == 11 + assert primitive_root(p**2) == 11 + raises(ValueError, lambda: primitive_root(-3)) + + assert is_quad_residue(3, 7) is False + assert is_quad_residue(10, 13) is True + assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139) + assert is_quad_residue(207, 251) is True + assert is_quad_residue(0, 1) is True + assert is_quad_residue(1, 1) is True + assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True + assert is_quad_residue(1, 4) is True + assert is_quad_residue(2, 27) is False + assert is_quad_residue(13122380800, 13604889600) is True + assert [j for j in range(14) if is_quad_residue(j, 14)] == \ + [0, 1, 2, 4, 7, 8, 9, 11] + raises(ValueError, lambda: is_quad_residue(1.1, 2)) + raises(ValueError, lambda: is_quad_residue(2, 0)) + + assert quadratic_residues(S.One) == [0] + assert quadratic_residues(1) == [0] + assert quadratic_residues(12) == [0, 1, 4, 9] + assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12] + assert [len(quadratic_residues(i)) for i in range(1, 20)] == \ + [1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10] + + assert list(sqrt_mod_iter(6, 2)) == [0] + assert sqrt_mod(3, 13) == 4 + assert sqrt_mod(3, -13) == 4 + assert sqrt_mod(6, 23) == 11 + assert sqrt_mod(345, 690) == 345 + assert sqrt_mod(67, 101) == None + assert sqrt_mod(1020, 104729) == None + + for p in range(3, 100): + d = defaultdict(list) + for i in range(p): + d[pow(i, 2, p)].append(i) + for i in range(1, p): + it = sqrt_mod_iter(i, p) + v = sqrt_mod(i, p, True) + if v: + v = sorted(v) + assert d[i] == v + else: + assert not d[i] + + assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24] + assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78] + assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240] + assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72] + assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\ + 126, 144, 153, 171, 180, 198, 207, 225, 234] + assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\ + 333, 396, 414, 477, 495, 558, 576, 639, 657, 720] + assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\ + 981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178] + + for a, p in [(26214400, 32768000000), (26214400, 16384000000), + (262144, 1048576), (87169610025, 163443018796875), + (22315420166400, 167365651248000000)]: + assert pow(sqrt_mod(a, p), 2, p) == a + + n = 70 + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2) + it = sqrt_mod_iter(a, p) + for i in range(10): + assert pow(next(it), 2, p) == a + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3) + it = sqrt_mod_iter(a, p) + for i in range(2): + assert pow(next(it), 2, p) == a + n = 100 + a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1) + it = sqrt_mod_iter(a, p) + for i in range(2): + assert pow(next(it), 2, p) == a + + assert type(next(sqrt_mod_iter(9, 27))) is int + assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1)) + assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1)) + + assert is_nthpow_residue(2, 1, 5) + + #issue 10816 + assert is_nthpow_residue(1, 0, 1) is False + assert is_nthpow_residue(1, 0, 2) is True + assert is_nthpow_residue(3, 0, 2) is True + assert is_nthpow_residue(0, 1, 8) is True + assert is_nthpow_residue(2, 3, 2) is True + assert is_nthpow_residue(2, 3, 9) is False + assert is_nthpow_residue(3, 5, 30) is True + assert is_nthpow_residue(21, 11, 20) is True + assert is_nthpow_residue(7, 10, 20) is False + assert is_nthpow_residue(5, 10, 20) is True + assert is_nthpow_residue(3, 10, 48) is False + assert is_nthpow_residue(1, 10, 40) is True + assert is_nthpow_residue(3, 10, 24) is False + assert is_nthpow_residue(1, 10, 24) is True + assert is_nthpow_residue(3, 10, 24) is False + assert is_nthpow_residue(2, 10, 48) is False + assert is_nthpow_residue(81, 3, 972) is False + assert is_nthpow_residue(243, 5, 5103) is True + assert is_nthpow_residue(243, 3, 1240029) is False + assert is_nthpow_residue(36010, 8, 87382) is True + assert is_nthpow_residue(28552, 6, 2218) is True + assert is_nthpow_residue(92712, 9, 50026) is True + x = {pow(i, 56, 1024) for i in range(1024)} + assert {a for a in range(1024) if is_nthpow_residue(a, 56, 1024)} == x + x = { pow(i, 256, 2048) for i in range(2048)} + assert {a for a in range(2048) if is_nthpow_residue(a, 256, 2048)} == x + x = { pow(i, 11, 324000) for i in range(1000)} + assert [ is_nthpow_residue(a, 11, 324000) for a in x] + x = { pow(i, 17, 22217575536) for i in range(1000)} + assert [ is_nthpow_residue(a, 17, 22217575536) for a in x] + assert is_nthpow_residue(676, 3, 5364) + assert is_nthpow_residue(9, 12, 36) + assert is_nthpow_residue(32, 10, 41) + assert is_nthpow_residue(4, 2, 64) + assert is_nthpow_residue(31, 4, 41) + assert not is_nthpow_residue(2, 2, 5) + assert is_nthpow_residue(8547, 12, 10007) + assert is_nthpow_residue(Dummy(even=True) + 3, 3, 2) == True + assert nthroot_mod(Dummy(odd=True), 3, 2) == 1 + + assert nthroot_mod(29, 31, 74) == [45] + assert nthroot_mod(1801, 11, 2663) == 44 + for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663), + (26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663), + (1714, 12, 2663), (28477, 9, 33343)]: + r = nthroot_mod(a, q, p) + assert pow(r, q, p) == a + assert nthroot_mod(11, 3, 109) is None + assert nthroot_mod(16, 5, 36, True) == [4, 22] + assert nthroot_mod(9, 16, 36, True) == [3, 9, 15, 21, 27, 33] + assert nthroot_mod(4, 3, 3249000) == [] + assert nthroot_mod(36010, 8, 87382, True) == [40208, 47174] + assert nthroot_mod(0, 12, 37, True) == [0] + assert nthroot_mod(0, 7, 100, True) == [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] + assert nthroot_mod(4, 4, 27, True) == [5, 22] + assert nthroot_mod(4, 4, 121, True) == [19, 102] + assert nthroot_mod(2, 3, 7, True) == [] + + for p in range(5, 100): + qv = range(3, p, 4) + for q in qv: + d = defaultdict(list) + for i in range(p): + d[pow(i, q, p)].append(i) + for a in range(1, p - 1): + res = nthroot_mod(a, q, p, True) + if d[a]: + assert d[a] == res + else: + assert res == [] + + assert legendre_symbol(5, 11) == 1 + assert legendre_symbol(25, 41) == 1 + assert legendre_symbol(67, 101) == -1 + assert legendre_symbol(0, 13) == 0 + assert legendre_symbol(9, 3) == 0 + raises(ValueError, lambda: legendre_symbol(2, 4)) + + assert jacobi_symbol(25, 41) == 1 + assert jacobi_symbol(-23, 83) == -1 + assert jacobi_symbol(3, 9) == 0 + assert jacobi_symbol(42, 97) == -1 + assert jacobi_symbol(3, 5) == -1 + assert jacobi_symbol(7, 9) == 1 + assert jacobi_symbol(0, 3) == 0 + assert jacobi_symbol(0, 1) == 1 + assert jacobi_symbol(2, 1) == 1 + assert jacobi_symbol(1, 3) == 1 + raises(ValueError, lambda: jacobi_symbol(3, 8)) + + assert mobius(13*7) == 1 + assert mobius(1) == 1 + assert mobius(13*7*5) == -1 + assert mobius(13**2) == 0 + raises(ValueError, lambda: mobius(-3)) + + p = Symbol('p', integer=True, positive=True, prime=True) + x = Symbol('x', positive=True) + i = Symbol('i', integer=True) + assert mobius(p) == -1 + raises(TypeError, lambda: mobius(x)) + raises(ValueError, lambda: mobius(i)) + + assert _discrete_log_trial_mul(587, 2**7, 2) == 7 + assert _discrete_log_trial_mul(941, 7**18, 7) == 18 + assert _discrete_log_trial_mul(389, 3**81, 3) == 81 + assert _discrete_log_trial_mul(191, 19**123, 19) == 123 + assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2 + assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19 + assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71 + assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321 + assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6 + assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19 + assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40 + assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333 + raises(ValueError, lambda: _discrete_log_pollard_rho(11, 7, 31, rseed=0)) + raises(ValueError, lambda: _discrete_log_pollard_rho(227, 3**7, 5, rseed=0)) + + assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9 + assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31 + assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98 + assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444 + assert discrete_log(587, 2**9, 2) == 9 + assert discrete_log(2456747, 3**51, 3) == 51 + assert discrete_log(32942478, 11**127, 11) == 127 + assert discrete_log(432751500361, 7**324, 7) == 324 + args = 5779, 3528, 6215 + assert discrete_log(*args) == 687 + assert discrete_log(*Tuple(*args)) == 687 + assert quadratic_congruence(400, 85, 125, 1600) == [295, 615, 935, 1255, 1575] + assert quadratic_congruence(3, 6, 5, 25) == [3, 20] + assert quadratic_congruence(120, 80, 175, 500) == [] + assert quadratic_congruence(15, 14, 7, 2) == [1] + assert quadratic_congruence(8, 15, 7, 29) == [10, 28] + assert quadratic_congruence(160, 200, 300, 461) == [144, 431] + assert quadratic_congruence(100000, 123456, 7415263, 48112959837082048697) == [30417843635344493501, 36001135160550533083] + assert quadratic_congruence(65, 121, 72, 277) == [249, 252] + assert quadratic_congruence(5, 10, 14, 2) == [0] + assert quadratic_congruence(10, 17, 19, 2) == [1] + assert quadratic_congruence(10, 14, 20, 2) == [0, 1] + assert polynomial_congruence(6*x**5 + 10*x**4 + 5*x**3 + x**2 + x + 1, + 972000) == [220999, 242999, 463999, 485999, 706999, 728999, 949999, 971999] + + assert polynomial_congruence(x**3 - 10*x**2 + 12*x - 82, 33075) == [30287] + assert polynomial_congruence(x**2 + x + 47, 2401) == [785, 1615] + assert polynomial_congruence(10*x**2 + 14*x + 20, 2) == [0, 1] + assert polynomial_congruence(x**3 + 3, 16) == [5] + assert polynomial_congruence(65*x**2 + 121*x + 72, 277) == [249, 252] + assert polynomial_congruence(x**4 - 4, 27) == [5, 22] + assert polynomial_congruence(35*x**3 - 6*x**2 - 567*x + 2308, 148225) == [86957, + 111157, 122531, 146731] + assert polynomial_congruence(x**16 - 9, 36) == [3, 9, 15, 21, 27, 33] + assert polynomial_congruence(x**6 - 2*x**5 - 35, 6125) == [3257] + raises(ValueError, lambda: polynomial_congruence(x**x, 6125)) + raises(ValueError, lambda: polynomial_congruence(x**i, 6125)) + raises(ValueError, lambda: polynomial_congruence(0.1*x**2 + 6, 100)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..980956273d8ab833d2ac31cbd2de59cf83209cda Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fccf9a6e9b8cd2ce201740701f9c60c1f4c928c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37fcfeb3c5613554ba45e167e68c7b6f2c2b645f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest1.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest1.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f58892f834f3862ed502fe0de330e17b9f9bda96 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest1.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest10.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest10.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6172b6f7c75113dd7ebcef508fb47d2360ab19e0 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest10.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6ad1ddaab53909484db91c6732c30deb97c1e3c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74ccb9f06aa7544c7c13824bb5ed1551d518812c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest7.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest7.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..123edbfb0822607499367871f89d48ed4a279994 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest7.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2544f5a3d60a62006e5f5587e31eaec9466ce774 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest9.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest9.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99a6dddf534183c9619aaadc554a7135333b3d69 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest9.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/tree.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/tree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc4779a1276f123484906e5e93b4b34f80a4c0ad Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/tree.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/util.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7e3a8c0861f3b4814588e2e645334ae8b8c9d5d Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/__pycache__/util.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fec5afe84a58f3d887a8c762692a3673a2b6d4c8 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__init__.py @@ -0,0 +1,14 @@ +from . import traverse +from .core import ( + condition, debug, multiplex, exhaust, notempty, + chain, onaction, sfilter, yieldify, do_one, identity) +from .tools import canon + +__all__ = [ + 'traverse', + + 'condition', 'debug', 'multiplex', 'exhaust', 'notempty', 'chain', + 'onaction', 'sfilter', 'yieldify', 'do_one', 'identity', + + 'canon', +] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867d617ef8f70c9159e766170dd5c305929025cf Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/core.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1492551a1e0400d09f482f2d99b9546bbcd7d734 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/core.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aca8a5fca2ba437e7c4a4bef972f56703f64342 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5972ca2172c84ee31efe29831993e241aa1e7b4 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/core.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/core.py new file mode 100644 index 0000000000000000000000000000000000000000..2dabaef69b60d994799f71414699223f84e1809b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/core.py @@ -0,0 +1,116 @@ +""" Generic SymPy-Independent Strategies """ + + +def identity(x): + yield x + + +def exhaust(brule): + """ Apply a branching rule repeatedly until it has no effect """ + def exhaust_brl(expr): + seen = {expr} + for nexpr in brule(expr): + if nexpr not in seen: + seen.add(nexpr) + yield from exhaust_brl(nexpr) + if seen == {expr}: + yield expr + return exhaust_brl + + +def onaction(brule, fn): + def onaction_brl(expr): + for result in brule(expr): + if result != expr: + fn(brule, expr, result) + yield result + return onaction_brl + + +def debug(brule, file=None): + """ Print the input and output expressions at each rule application """ + if not file: + from sys import stdout + file = stdout + + def write(brl, expr, result): + file.write("Rule: %s\n" % brl.__name__) + file.write("In: %s\nOut: %s\n\n" % (expr, result)) + + return onaction(brule, write) + + +def multiplex(*brules): + """ Multiplex many branching rules into one """ + def multiplex_brl(expr): + seen = set() + for brl in brules: + for nexpr in brl(expr): + if nexpr not in seen: + seen.add(nexpr) + yield nexpr + return multiplex_brl + + +def condition(cond, brule): + """ Only apply branching rule if condition is true """ + def conditioned_brl(expr): + if cond(expr): + yield from brule(expr) + else: + pass + return conditioned_brl + + +def sfilter(pred, brule): + """ Yield only those results which satisfy the predicate """ + def filtered_brl(expr): + yield from filter(pred, brule(expr)) + return filtered_brl + + +def notempty(brule): + def notempty_brl(expr): + yielded = False + for nexpr in brule(expr): + yielded = True + yield nexpr + if not yielded: + yield expr + return notempty_brl + + +def do_one(*brules): + """ Execute one of the branching rules """ + def do_one_brl(expr): + yielded = False + for brl in brules: + for nexpr in brl(expr): + yielded = True + yield nexpr + if yielded: + return + return do_one_brl + + +def chain(*brules): + """ + Compose a sequence of brules so that they apply to the expr sequentially + """ + def chain_brl(expr): + if not brules: + yield expr + return + + head, tail = brules[0], brules[1:] + for nexpr in head(expr): + yield from chain(*tail)(nexpr) + + return chain_brl + + +def yieldify(rl): + """ Turn a rule into a branching rule """ + def brl(expr): + yield rl(expr) + return brl diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8f65a40e2fc302c5b308fb2146aca48cf9c0eb9 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26f80b7cc84ec501bd45a0e4e9fe1a93e08659c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..312d78b1d9c9dc3a2edf0ad3a91648e341a5c998 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64bdc78864b721ed0e214555c323ecf594120b3b Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_core.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..ac620b0afb6dbadc4d97b29ddbb341cd920b6588 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_core.py @@ -0,0 +1,117 @@ +from sympy.strategies.branch.core import ( + exhaust, debug, multiplex, condition, notempty, chain, onaction, sfilter, + yieldify, do_one, identity) + + +def posdec(x): + if x > 0: + yield x - 1 + else: + yield x + + +def branch5(x): + if 0 < x < 5: + yield x - 1 + elif 5 < x < 10: + yield x + 1 + elif x == 5: + yield x + 1 + yield x - 1 + else: + yield x + + +def even(x): + return x % 2 == 0 + + +def inc(x): + yield x + 1 + + +def one_to_n(n): + yield from range(n) + + +def test_exhaust(): + brl = exhaust(branch5) + assert set(brl(3)) == {0} + assert set(brl(7)) == {10} + assert set(brl(5)) == {0, 10} + + +def test_debug(): + from io import StringIO + file = StringIO() + rl = debug(posdec, file) + list(rl(5)) + log = file.getvalue() + file.close() + + assert posdec.__name__ in log + assert '5' in log + assert '4' in log + + +def test_multiplex(): + brl = multiplex(posdec, branch5) + assert set(brl(3)) == {2} + assert set(brl(7)) == {6, 8} + assert set(brl(5)) == {4, 6} + + +def test_condition(): + brl = condition(even, branch5) + assert set(brl(4)) == set(branch5(4)) + assert set(brl(5)) == set() + + +def test_sfilter(): + brl = sfilter(even, one_to_n) + assert set(brl(10)) == {0, 2, 4, 6, 8} + + +def test_notempty(): + def ident_if_even(x): + if even(x): + yield x + + brl = notempty(ident_if_even) + assert set(brl(4)) == {4} + assert set(brl(5)) == {5} + + +def test_chain(): + assert list(chain()(2)) == [2] # identity + assert list(chain(inc, inc)(2)) == [4] + assert list(chain(branch5, inc)(4)) == [4] + assert set(chain(branch5, inc)(5)) == {5, 7} + assert list(chain(inc, branch5)(5)) == [7] + + +def test_onaction(): + L = [] + + def record(fn, input, output): + L.append((input, output)) + + list(onaction(inc, record)(2)) + assert L == [(2, 3)] + + list(onaction(identity, record)(2)) + assert L == [(2, 3)] + + +def test_yieldify(): + yinc = yieldify(lambda x: x + 1) + assert list(yinc(3)) == [4] + + +def test_do_one(): + def bad(expr): + raise ValueError + + assert list(do_one(inc)(3)) == [4] + assert list(do_one(inc, bad)(3)) == [4] + assert list(do_one(inc, posdec)(3)) == [4] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_tools.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bd224030c337f0a000d94f6e7e65f3b8bd118f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_tools.py @@ -0,0 +1,42 @@ +from sympy.strategies.branch.tools import canon +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.singleton import S + + +def posdec(x): + if isinstance(x, Integer) and x > 0: + yield x - 1 + else: + yield x + + +def branch5(x): + if isinstance(x, Integer): + if 0 < x < 5: + yield x - 1 + elif 5 < x < 10: + yield x + 1 + elif x == 5: + yield x + 1 + yield x - 1 + else: + yield x + + +def test_zero_ints(): + expr = Basic(S(2), Basic(S(5), S(3)), S(8)) + expected = {Basic(S(0), Basic(S(0), S(0)), S(0))} + + brl = canon(posdec) + assert set(brl(expr)) == expected + + +def test_split5(): + expr = Basic(S(2), Basic(S(5), S(3)), S(8)) + expected = { + Basic(S(0), Basic(S(0), S(0)), S(10)), + Basic(S(0), Basic(S(10), S(0)), S(10))} + + brl = canon(branch5) + assert set(brl(expr)) == expected diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_traverse.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..e051928210981223004de28b8c617d0438e11ac6 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tests/test_traverse.py @@ -0,0 +1,53 @@ +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.singleton import S +from sympy.strategies.branch.traverse import top_down, sall +from sympy.strategies.branch.core import do_one, identity + + +def inc(x): + if isinstance(x, Integer): + yield x + 1 + + +def test_top_down_easy(): + expr = Basic(S(1), S(2)) + expected = Basic(S(2), S(3)) + brl = top_down(inc) + + assert set(brl(expr)) == {expected} + + +def test_top_down_big_tree(): + expr = Basic(S(1), Basic(S(2)), Basic(S(3), Basic(S(4)), S(5))) + expected = Basic(S(2), Basic(S(3)), Basic(S(4), Basic(S(5)), S(6))) + brl = top_down(inc) + + assert set(brl(expr)) == {expected} + + +def test_top_down_harder_function(): + def split5(x): + if x == 5: + yield x - 1 + yield x + 1 + + expr = Basic(Basic(S(5), S(6)), S(1)) + expected = {Basic(Basic(S(4), S(6)), S(1)), Basic(Basic(S(6), S(6)), S(1))} + brl = top_down(split5) + + assert set(brl(expr)) == expected + + +def test_sall(): + expr = Basic(S(1), S(2)) + expected = Basic(S(2), S(3)) + brl = sall(inc) + + assert list(brl(expr)) == [expected] + + expr = Basic(S(1), S(2), Basic(S(3), S(4))) + expected = Basic(S(2), S(3), Basic(S(3), S(4))) + brl = sall(do_one(inc, identity)) + + assert list(brl(expr)) == [expected] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tools.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c9097323a7962080ae4497ead976818e386518 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/tools.py @@ -0,0 +1,12 @@ +from .core import exhaust, multiplex +from .traverse import top_down + + +def canon(*rules): + """ Strategy for canonicalization + + Apply each branching rule in a top-down fashion through the tree. + Multiplex through all branching rule traversals + Keep doing this until there is no change. + """ + return exhaust(multiplex(*map(top_down, rules))) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/traverse.py b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..28b7098dbda401fc0f0b6d27988d8c37e2f231ae --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/strategies/branch/traverse.py @@ -0,0 +1,25 @@ +""" Branching Strategies to Traverse a Tree """ +from itertools import product +from sympy.strategies.util import basic_fns +from .core import chain, identity, do_one + + +def top_down(brule, fns=basic_fns): + """ Apply a rule down a tree running it on the top nodes first """ + return chain(do_one(brule, identity), + lambda expr: sall(top_down(brule, fns), fns)(expr)) + + +def sall(brule, fns=basic_fns): + """ Strategic all - apply rule to args """ + op, new, children, leaf = map(fns.get, ('op', 'new', 'children', 'leaf')) + + def all_rl(expr): + if leaf(expr): + yield expr + else: + myop = op(expr) + argss = product(*map(brule, children(expr))) + for args in argss: + yield new(myop, *args) + return all_rl