nitroacid commited on
Commit
f47c3f5
·
verified ·
1 Parent(s): 6ab718d

Upload folder using huggingface_hub (part 31)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +17 -0
  2. .venv/Lib/site-packages/sympy/ntheory/factor_.py +2841 -0
  3. .venv/Lib/site-packages/sympy/ntheory/generate.py +1157 -0
  4. .venv/Lib/site-packages/sympy/ntheory/modular.py +291 -0
  5. .venv/Lib/site-packages/sympy/ntheory/multinomial.py +188 -0
  6. .venv/Lib/site-packages/sympy/ntheory/partitions_.py +277 -0
  7. .venv/Lib/site-packages/sympy/ntheory/primetest.py +830 -0
  8. .venv/Lib/site-packages/sympy/ntheory/qs.py +451 -0
  9. .venv/Lib/site-packages/sympy/ntheory/residue_ntheory.py +1963 -0
  10. .venv/Lib/site-packages/sympy/ntheory/tests/__init__.py +0 -0
  11. .venv/Lib/site-packages/sympy/ntheory/tests/test_bbp_pi.py +134 -0
  12. .venv/Lib/site-packages/sympy/ntheory/tests/test_continued_fraction.py +77 -0
  13. .venv/Lib/site-packages/sympy/ntheory/tests/test_digits.py +55 -0
  14. .venv/Lib/site-packages/sympy/ntheory/tests/test_ecm.py +63 -0
  15. .venv/Lib/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py +49 -0
  16. .venv/Lib/site-packages/sympy/ntheory/tests/test_elliptic_curve.py +20 -0
  17. .venv/Lib/site-packages/sympy/ntheory/tests/test_factor_.py +702 -0
  18. .venv/Lib/site-packages/sympy/ntheory/tests/test_generate.py +285 -0
  19. .venv/Lib/site-packages/sympy/ntheory/tests/test_hypothesis.py +24 -0
  20. .venv/Lib/site-packages/sympy/ntheory/tests/test_modular.py +34 -0
  21. .venv/Lib/site-packages/sympy/ntheory/tests/test_multinomial.py +48 -0
  22. .venv/Lib/site-packages/sympy/ntheory/tests/test_partitions.py +28 -0
  23. .venv/Lib/site-packages/sympy/ntheory/tests/test_primetest.py +235 -0
  24. .venv/Lib/site-packages/sympy/ntheory/tests/test_qs.py +110 -0
  25. .venv/Lib/site-packages/sympy/ntheory/tests/test_residue.py +349 -0
  26. .venv/Lib/site-packages/sympy/parsing/__init__.py +4 -0
  27. .venv/Lib/site-packages/sympy/parsing/__pycache__/__init__.cpython-312.pyc +0 -0
  28. .venv/Lib/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-312.pyc +0 -0
  29. .venv/Lib/site-packages/sympy/parsing/ast_parser.py +79 -0
  30. .venv/Lib/site-packages/sympy/parsing/autolev/Autolev.g4 +118 -0
  31. .venv/Lib/site-packages/sympy/parsing/autolev/__init__.py +97 -0
  32. .venv/Lib/site-packages/sympy/parsing/autolev/_antlr/__init__.py +5 -0
  33. .venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py +253 -0
  34. .venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py +421 -0
  35. .venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py +0 -0
  36. .venv/Lib/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py +86 -0
  37. .venv/Lib/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py +0 -0
  38. .venv/Lib/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py +38 -0
  39. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/README.txt +9 -0
  40. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al +33 -0
  41. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py +55 -0
  42. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al +25 -0
  43. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py +39 -0
  44. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al +19 -0
  45. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py +31 -0
  46. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al +20 -0
  47. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py +36 -0
  48. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest1.al +8 -0
  49. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py +15 -0
  50. .venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al +58 -0
.gitattributes CHANGED
@@ -581,3 +581,20 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
581
  .venv/Lib/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
582
  .venv/Lib/site-packages/sympy/logic/__pycache__/boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
583
  .venv/Lib/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
  .venv/Lib/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
582
  .venv/Lib/site-packages/sympy/logic/__pycache__/boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
583
  .venv/Lib/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
584
+ .venv/Lib/site-packages/sympy/plotting/__pycache__/series.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
585
+ .venv/Lib/site-packages/sympy/polys/__pycache__/compatibility.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
586
+ .venv/Lib/site-packages/sympy/polys/__pycache__/polyclasses.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
587
+ .venv/Lib/site-packages/sympy/polys/__pycache__/polyquinticconst.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
588
+ .venv/Lib/site-packages/sympy/polys/__pycache__/polytools.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
589
+ .venv/Lib/site-packages/sympy/polys/__pycache__/rings.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
590
+ .venv/Lib/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
591
+ .venv/Lib/site-packages/sympy/printing/__pycache__/latex.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
592
+ .venv/Lib/site-packages/sympy/printing/__pycache__/mathml.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
593
+ .venv/Lib/site-packages/sympy/printing/pretty/__pycache__/pretty.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
594
+ .venv/Lib/site-packages/sympy/sets/__pycache__/sets.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
595
+ .venv/Lib/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
596
+ .venv/Lib/site-packages/sympy/solvers/__pycache__/solvers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
597
+ .venv/Lib/site-packages/sympy/solvers/__pycache__/solveset.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
598
+ .venv/Lib/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
599
+ .venv/Lib/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
600
+ .venv/Lib/site-packages/sympy/solvers/ode/__pycache__/single.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/Lib/site-packages/sympy/ntheory/factor_.py ADDED
@@ -0,0 +1,2841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Integer factorization
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from bisect import bisect_left
7
+ from collections import defaultdict, OrderedDict
8
+ from collections.abc import MutableMapping
9
+ import math
10
+
11
+ from sympy.core.containers import Dict
12
+ from sympy.core.mul import Mul
13
+ from sympy.core.numbers import Rational, Integer
14
+ from sympy.core.intfunc import num_digits
15
+ from sympy.core.power import Pow
16
+ from sympy.core.random import _randint
17
+ from sympy.core.singleton import S
18
+ from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
19
+ sqrtrem, iroot, bit_scan1, remove)
20
+ from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
21
+ from .generate import sieve, primerange, nextprime
22
+ from .digits import digits
23
+ from sympy.utilities.decorator import deprecated
24
+ from sympy.utilities.iterables import flatten
25
+ from sympy.utilities.misc import as_int, filldedent
26
+ from .ecm import _ecm_one_factor
27
+
28
+
29
+ def smoothness(n):
30
+ """
31
+ Return the B-smooth and B-power smooth values of n.
32
+
33
+ The smoothness of n is the largest prime factor of n; the power-
34
+ smoothness is the largest divisor raised to its multiplicity.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.ntheory.factor_ import smoothness
40
+ >>> smoothness(2**7*3**2)
41
+ (3, 128)
42
+ >>> smoothness(2**4*13)
43
+ (13, 16)
44
+ >>> smoothness(2)
45
+ (2, 2)
46
+
47
+ See Also
48
+ ========
49
+
50
+ factorint, smoothness_p
51
+ """
52
+
53
+ if n == 1:
54
+ return (1, 1) # not prime, but otherwise this causes headaches
55
+ facs = factorint(n)
56
+ return max(facs), max(m**facs[m] for m in facs)
57
+
58
+
59
+ def smoothness_p(n, m=-1, power=0, visual=None):
60
+ """
61
+ Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
62
+ where:
63
+
64
+ 1. p**M is the base-p divisor of n
65
+ 2. sm(p + m) is the smoothness of p + m (m = -1 by default)
66
+ 3. psm(p + m) is the power smoothness of p + m
67
+
68
+ The list is sorted according to smoothness (default) or by power smoothness
69
+ if power=1.
70
+
71
+ The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
72
+ factor govern the results that are obtained from the p +/- 1 type factoring
73
+ methods.
74
+
75
+ >>> from sympy.ntheory.factor_ import smoothness_p, factorint
76
+ >>> smoothness_p(10431, m=1)
77
+ (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
78
+ >>> smoothness_p(10431)
79
+ (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
80
+ >>> smoothness_p(10431, power=1)
81
+ (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
82
+
83
+ If visual=True then an annotated string will be returned:
84
+
85
+ >>> print(smoothness_p(21477639576571, visual=1))
86
+ p**i=4410317**1 has p-1 B=1787, B-pow=1787
87
+ p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
88
+
89
+ This string can also be generated directly from a factorization dictionary
90
+ and vice versa:
91
+
92
+ >>> factorint(17*9)
93
+ {3: 2, 17: 1}
94
+ >>> smoothness_p(_)
95
+ 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
96
+ >>> smoothness_p(_)
97
+ {3: 2, 17: 1}
98
+
99
+ The table of the output logic is:
100
+
101
+ ====== ====== ======= =======
102
+ | Visual
103
+ ------ ----------------------
104
+ Input True False other
105
+ ====== ====== ======= =======
106
+ dict str tuple str
107
+ str str tuple dict
108
+ tuple str tuple str
109
+ n str tuple tuple
110
+ mul str tuple tuple
111
+ ====== ====== ======= =======
112
+
113
+ See Also
114
+ ========
115
+
116
+ factorint, smoothness
117
+ """
118
+
119
+ # visual must be True, False or other (stored as None)
120
+ if visual in (1, 0):
121
+ visual = bool(visual)
122
+ elif visual not in (True, False):
123
+ visual = None
124
+
125
+ if isinstance(n, str):
126
+ if visual:
127
+ return n
128
+ d = {}
129
+ for li in n.splitlines():
130
+ k, v = [int(i) for i in
131
+ li.split('has')[0].split('=')[1].split('**')]
132
+ d[k] = v
133
+ if visual is not True and visual is not False:
134
+ return d
135
+ return smoothness_p(d, visual=False)
136
+ elif not isinstance(n, tuple):
137
+ facs = factorint(n, visual=False)
138
+
139
+ if power:
140
+ k = -1
141
+ else:
142
+ k = 1
143
+ if isinstance(n, tuple):
144
+ rv = n
145
+ else:
146
+ rv = (m, sorted([(f,
147
+ tuple([M] + list(smoothness(f + m))))
148
+ for f, M in list(facs.items())],
149
+ key=lambda x: (x[1][k], x[0])))
150
+
151
+ if visual is False or (visual is not True) and (type(n) in [int, Mul]):
152
+ return rv
153
+ lines = []
154
+ for dat in rv[1]:
155
+ dat = flatten(dat)
156
+ dat.insert(2, m)
157
+ lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
158
+ return '\n'.join(lines)
159
+
160
+
161
+ def multiplicity(p, n):
162
+ """
163
+ Find the greatest integer m such that p**m divides n.
164
+
165
+ Examples
166
+ ========
167
+
168
+ >>> from sympy import multiplicity, Rational
169
+ >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
170
+ [0, 1, 2, 3, 3]
171
+ >>> multiplicity(3, Rational(1, 9))
172
+ -2
173
+
174
+ Note: when checking for the multiplicity of a number in a
175
+ large factorial it is most efficient to send it as an unevaluated
176
+ factorial or to call ``multiplicity_in_factorial`` directly:
177
+
178
+ >>> from sympy.ntheory import multiplicity_in_factorial
179
+ >>> from sympy import factorial
180
+ >>> p = factorial(25)
181
+ >>> n = 2**100
182
+ >>> nfac = factorial(n, evaluate=False)
183
+ >>> multiplicity(p, nfac)
184
+ 52818775009509558395695966887
185
+ >>> _ == multiplicity_in_factorial(p, n)
186
+ True
187
+
188
+ See Also
189
+ ========
190
+
191
+ trailing
192
+
193
+ """
194
+ try:
195
+ p, n = as_int(p), as_int(n)
196
+ except ValueError:
197
+ from sympy.functions.combinatorial.factorials import factorial
198
+ if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
199
+ p = Rational(p)
200
+ n = Rational(n)
201
+ if p.q == 1:
202
+ if n.p == 1:
203
+ return -multiplicity(p.p, n.q)
204
+ return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
205
+ elif p.p == 1:
206
+ return multiplicity(p.q, n.q)
207
+ else:
208
+ like = min(
209
+ multiplicity(p.p, n.p),
210
+ multiplicity(p.q, n.q))
211
+ cross = min(
212
+ multiplicity(p.q, n.p),
213
+ multiplicity(p.p, n.q))
214
+ return like - cross
215
+ elif (isinstance(p, (SYMPY_INTS, Integer)) and
216
+ isinstance(n, factorial) and
217
+ isinstance(n.args[0], Integer) and
218
+ n.args[0] >= 0):
219
+ return multiplicity_in_factorial(p, n.args[0])
220
+ raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
221
+
222
+ if n == 0:
223
+ raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
224
+ return remove(n, p)[1]
225
+
226
+
227
+ def multiplicity_in_factorial(p, n):
228
+ """return the largest integer ``m`` such that ``p**m`` divides ``n!``
229
+ without calculating the factorial of ``n``.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ p : Integer
235
+ positive integer
236
+ n : Integer
237
+ non-negative integer
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy.ntheory import multiplicity_in_factorial
243
+ >>> from sympy import factorial
244
+
245
+ >>> multiplicity_in_factorial(2, 3)
246
+ 1
247
+
248
+ An instructive use of this is to tell how many trailing zeros
249
+ a given factorial has. For example, there are 6 in 25!:
250
+
251
+ >>> factorial(25)
252
+ 15511210043330985984000000
253
+ >>> multiplicity_in_factorial(10, 25)
254
+ 6
255
+
256
+ For large factorials, it is much faster/feasible to use
257
+ this function rather than computing the actual factorial:
258
+
259
+ >>> multiplicity_in_factorial(factorial(25), 2**100)
260
+ 52818775009509558395695966887
261
+
262
+ See Also
263
+ ========
264
+
265
+ multiplicity
266
+
267
+ """
268
+
269
+ p, n = as_int(p), as_int(n)
270
+
271
+ if p <= 0:
272
+ raise ValueError('expecting positive integer got %s' % p )
273
+
274
+ if n < 0:
275
+ raise ValueError('expecting non-negative integer got %s' % n )
276
+
277
+ # keep only the largest of a given multiplicity since those
278
+ # of a given multiplicity will be goverened by the behavior
279
+ # of the largest factor
280
+ f = defaultdict(int)
281
+ for k, v in factorint(p).items():
282
+ f[v] = max(k, f[v])
283
+ # multiplicity of p in n! depends on multiplicity
284
+ # of prime `k` in p, so we floor divide by `v`
285
+ # and keep it if smaller than the multiplicity of p
286
+ # seen so far
287
+ return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
288
+
289
+
290
+ def _perfect_power(n, next_p=2):
291
+ """ Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
292
+ perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
293
+
294
+ Explanation
295
+ ===========
296
+
297
+ This is a low-level helper for ``perfect_power``, for internal use.
298
+
299
+ Parameters
300
+ ==========
301
+
302
+ n : int
303
+ assume that n is a nonnegative integer
304
+ next_p : int
305
+ Assume that n has no factor less than next_p.
306
+ i.e., all(n % p for p in range(2, next_p)) is True
307
+
308
+ Examples
309
+ ========
310
+ >>> from sympy.ntheory.factor_ import _perfect_power
311
+ >>> _perfect_power(16)
312
+ (2, 4)
313
+ >>> _perfect_power(17)
314
+ False
315
+
316
+ """
317
+ if n <= 3:
318
+ return False
319
+
320
+ factors = {}
321
+ g = 0
322
+ multi = 1
323
+
324
+ def done(n, factors, g, multi):
325
+ g = gcd(g, multi)
326
+ if g == 1:
327
+ return False
328
+ factors[n] = multi
329
+ return math.prod(p**(e//g) for p, e in factors.items()), g
330
+
331
+ # If n is small, only trial factoring is faster
332
+ if n <= 1_000_000:
333
+ n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
334
+ if n > 1:
335
+ return False
336
+ g = gcd(*factors.values())
337
+ if g == 1:
338
+ return False
339
+ return math.prod(p**(e//g) for p, e in factors.items()), g
340
+
341
+ # divide by 2
342
+ if next_p < 3:
343
+ g = bit_scan1(n)
344
+ if g:
345
+ if g == 1:
346
+ return False
347
+ n >>= g
348
+ factors[2] = g
349
+ if n == 1:
350
+ return 2, g
351
+ else:
352
+ # If `m**g`, then we have found perfect power.
353
+ # Otherwise, there is no possibility of perfect power, especially if `g` is prime.
354
+ m, _exact = iroot(n, g)
355
+ if _exact:
356
+ return 2*m, g
357
+ elif isprime(g):
358
+ return False
359
+ next_p = 3
360
+
361
+ # square number?
362
+ while n & 7 == 1: # n % 8 == 1:
363
+ m, _exact = iroot(n, 2)
364
+ if _exact:
365
+ n = m
366
+ multi <<= 1
367
+ else:
368
+ break
369
+ if n < next_p**3:
370
+ return done(n, factors, g, multi)
371
+
372
+ # trial factoring
373
+ # Since the maximum value an exponent can take is `log_{next_p}(n)`,
374
+ # the number of exponents to be checked can be reduced by performing a trial factoring.
375
+ # The value of `tf_max` needs more consideration.
376
+ tf_max = n.bit_length()//27 + 24
377
+ if next_p < tf_max:
378
+ for p in primerange(next_p, tf_max):
379
+ m, t = remove(n, p)
380
+ if t:
381
+ n = m
382
+ t *= multi
383
+ _g = gcd(g, t)
384
+ if _g == 1:
385
+ return False
386
+ factors[p] = t
387
+ if n == 1:
388
+ return math.prod(p**(e//_g)
389
+ for p, e in factors.items()), _g
390
+ elif g == 0 or _g < g: # If g is updated
391
+ g = _g
392
+ m, _exact = iroot(n**multi, g)
393
+ if _exact:
394
+ return m * math.prod(p**(e//g)
395
+ for p, e in factors.items()), g
396
+ elif isprime(g):
397
+ return False
398
+ next_p = tf_max
399
+ if n < next_p**3:
400
+ return done(n, factors, g, multi)
401
+
402
+ # check iroot
403
+ if g:
404
+ # If g is non-zero, the exponent is a divisor of g.
405
+ # 2 can be omitted since it has already been checked.
406
+ prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
407
+ else:
408
+ # The maximum possible value of the exponent is `log_{next_p}(n)`.
409
+ # To compensate for the presence of computational error, 2 is added.
410
+ prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
411
+ logn = math.log2(n)
412
+ threshold = logn / 40 # Threshold for direct calculation
413
+ for p in prime_iter:
414
+ if threshold < p:
415
+ # If p is large, find the power root p directly without `iroot`.
416
+ while True:
417
+ b = pow(2, logn / p)
418
+ rb = int(b + 0.5)
419
+ if abs(rb - b) < 0.01 and rb**p == n:
420
+ n = rb
421
+ multi *= p
422
+ logn = math.log2(n)
423
+ else:
424
+ break
425
+ else:
426
+ while True:
427
+ m, _exact = iroot(n, p)
428
+ if _exact:
429
+ n = m
430
+ multi *= p
431
+ logn = math.log2(n)
432
+ else:
433
+ break
434
+ if n < next_p**(p + 2):
435
+ break
436
+ return done(n, factors, g, multi)
437
+
438
+
439
+ def perfect_power(n, candidates=None, big=True, factor=True):
440
+ """
441
+ Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
442
+ perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
443
+ perfect power). A ValueError is raised if ``n`` is not Rational.
444
+
445
+ By default, the base is recursively decomposed and the exponents
446
+ collected so the largest possible ``e`` is sought. If ``big=False``
447
+ then the smallest possible ``e`` (thus prime) will be chosen.
448
+
449
+ If ``factor=True`` then simultaneous factorization of ``n`` is
450
+ attempted since finding a factor indicates the only possible root
451
+ for ``n``. This is True by default since only a few small factors will
452
+ be tested in the course of searching for the perfect power.
453
+
454
+ The use of ``candidates`` is primarily for internal use; if provided,
455
+ False will be returned if ``n`` cannot be written as a power with one
456
+ of the candidates as an exponent and factoring (beyond testing for
457
+ a factor of 2) will not be attempted.
458
+
459
+ Examples
460
+ ========
461
+
462
+ >>> from sympy import perfect_power, Rational
463
+ >>> perfect_power(16)
464
+ (2, 4)
465
+ >>> perfect_power(16, big=False)
466
+ (4, 2)
467
+
468
+ Negative numbers can only have odd perfect powers:
469
+
470
+ >>> perfect_power(-4)
471
+ False
472
+ >>> perfect_power(-8)
473
+ (-2, 3)
474
+
475
+ Rationals are also recognized:
476
+
477
+ >>> perfect_power(Rational(1, 2)**3)
478
+ (1/2, 3)
479
+ >>> perfect_power(Rational(-3, 2)**3)
480
+ (-3/2, 3)
481
+
482
+ Notes
483
+ =====
484
+
485
+ To know whether an integer is a perfect power of 2 use
486
+
487
+ >>> is2pow = lambda n: bool(n and not n & (n - 1))
488
+ >>> [(i, is2pow(i)) for i in range(5)]
489
+ [(0, False), (1, True), (2, True), (3, False), (4, True)]
490
+
491
+ It is not necessary to provide ``candidates``. When provided
492
+ it will be assumed that they are ints. The first one that is
493
+ larger than the computed maximum possible exponent will signal
494
+ failure for the routine.
495
+
496
+ >>> perfect_power(3**8, [9])
497
+ False
498
+ >>> perfect_power(3**8, [2, 4, 8])
499
+ (3, 8)
500
+ >>> perfect_power(3**8, [4, 8], big=False)
501
+ (9, 4)
502
+
503
+ See Also
504
+ ========
505
+ sympy.core.intfunc.integer_nthroot
506
+ sympy.ntheory.primetest.is_square
507
+ """
508
+ # negative handling
509
+ if n < 0:
510
+ if candidates is None:
511
+ pp = perfect_power(-n, big=True, factor=factor)
512
+ if not pp:
513
+ return False
514
+
515
+ b, e = pp
516
+ e2 = e & (-e)
517
+ b, e = b ** e2, e // e2
518
+
519
+ if e <= 1:
520
+ return False
521
+
522
+ if big or isprime(e):
523
+ return -b, e
524
+
525
+ for p in primerange(3, e + 1):
526
+ if e % p == 0:
527
+ return - b ** (e // p), p
528
+
529
+ odd_candidates = {i for i in candidates if i % 2}
530
+ if not odd_candidates:
531
+ return False
532
+
533
+ pp = perfect_power(-n, odd_candidates, big, factor)
534
+ if pp:
535
+ return -pp[0], pp[1]
536
+
537
+ return False
538
+
539
+ # non-integer handling
540
+ if isinstance(n, Rational) and not isinstance(n, Integer):
541
+ p, q = n.p, n.q
542
+
543
+ if p == 1:
544
+ qq = perfect_power(q, candidates, big, factor)
545
+ return (S.One / qq[0], qq[1]) if qq is not False else False
546
+
547
+ if not (pp:=perfect_power(p, factor=factor)):
548
+ return False
549
+ if not (qq:=perfect_power(q, factor=factor)):
550
+ return False
551
+ (num_base, num_exp), (den_base, den_exp) = pp, qq
552
+
553
+ def compute_tuple(exponent):
554
+ """Helper to compute final result given an exponent"""
555
+ new_num = num_base ** (num_exp // exponent)
556
+ new_den = den_base ** (den_exp // exponent)
557
+ return n.func(new_num, new_den), exponent
558
+
559
+ if candidates:
560
+ valid_candidates = [i for i in candidates
561
+ if num_exp % i == 0 and den_exp % i == 0]
562
+ if not valid_candidates:
563
+ return False
564
+
565
+ e = max(valid_candidates) if big else min(valid_candidates)
566
+ return compute_tuple(e)
567
+
568
+ g = math.gcd(num_exp, den_exp)
569
+ if g == 1:
570
+ return False
571
+
572
+ if big:
573
+ return compute_tuple(g)
574
+
575
+ e = next(p for p in primerange(2, g + 1) if g % p == 0)
576
+ return compute_tuple(e)
577
+
578
+ if candidates is not None:
579
+ candidates = set(candidates)
580
+
581
+ # positive integer handling
582
+ n = as_int(n)
583
+
584
+ if candidates is None and big:
585
+ return _perfect_power(n)
586
+
587
+ if n <= 3:
588
+ # no unique exponent for 0, 1
589
+ # 2 and 3 have exponents of 1
590
+ return False
591
+ logn = math.log2(n)
592
+ max_possible = int(logn) + 2 # only check values less than this
593
+ not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
594
+ min_possible = 2 + not_square
595
+ if not candidates:
596
+ candidates = primerange(min_possible, max_possible)
597
+ else:
598
+ candidates = sorted([i for i in candidates
599
+ if min_possible <= i < max_possible])
600
+ if n%2 == 0:
601
+ e = bit_scan1(n)
602
+ candidates = [i for i in candidates if e%i == 0]
603
+ if big:
604
+ candidates = reversed(candidates)
605
+ for e in candidates:
606
+ r, ok = iroot(n, e)
607
+ if ok:
608
+ return int(r), e
609
+ return False
610
+
611
+ def _factors():
612
+ rv = 2 + n % 2
613
+ while True:
614
+ yield rv
615
+ rv = nextprime(rv)
616
+
617
+ for fac, e in zip(_factors(), candidates):
618
+ # see if there is a factor present
619
+ if factor and n % fac == 0:
620
+ # find what the potential power is
621
+ e = remove(n, fac)[1]
622
+ # if it's a trivial power we are done
623
+ if e == 1:
624
+ return False
625
+
626
+ # maybe the e-th root of n is exact
627
+ r, exact = iroot(n, e)
628
+ if not exact:
629
+ # Having a factor, we know that e is the maximal
630
+ # possible value for a root of n.
631
+ # If n = fac**e*m can be written as a perfect
632
+ # power then see if m can be written as r**E where
633
+ # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
634
+ m = n//fac**e
635
+ rE = perfect_power(m, candidates=divisors(e, generator=True))
636
+ if not rE:
637
+ return False
638
+ else:
639
+ r, E = rE
640
+ r, e = fac**(e//E)*r, E
641
+ if not big:
642
+ e0 = primefactors(e)
643
+ if e0[0] != e:
644
+ r, e = r**(e//e0[0]), e0[0]
645
+ return int(r), e
646
+
647
+ # Weed out downright impossible candidates
648
+ if logn/e < 40:
649
+ b = 2.0**(logn/e)
650
+ if abs(int(b + 0.5) - b) > 0.01:
651
+ continue
652
+
653
+ # now see if the plausible e makes a perfect power
654
+ r, exact = iroot(n, e)
655
+ if exact:
656
+ if big:
657
+ m = perfect_power(r, big=big, factor=factor)
658
+ if m:
659
+ r, e = m[0], e*m[1]
660
+ return int(r), e
661
+
662
+ return False
663
+
664
+
665
+ class FactorCache(MutableMapping):
666
+ """ Provides a cache for prime factors.
667
+ ``factor_cache`` is pre-prepared as an instance of ``FactorCache``,
668
+ and ``factorint`` internally references it to speed up
669
+ the factorization of prime factors.
670
+
671
+ While cache is automatically added during the execution of ``factorint``,
672
+ users can also manually add prime factors independently.
673
+
674
+ >>> from sympy import factor_cache
675
+ >>> factor_cache[15] = 5
676
+
677
+ Furthermore, by customizing ``get_external``,
678
+ it is also possible to use external databases.
679
+ The following is an example using http://factordb.com .
680
+
681
+ .. code-block:: python
682
+
683
+ import requests
684
+ from sympy import factor_cache
685
+
686
+ def get_external(self, n: int) -> list[int] | None:
687
+ res = requests.get("http://factordb.com/api", params={"query": str(n)})
688
+ if res.status_code != requests.codes.ok:
689
+ return None
690
+ j = res.json()
691
+ if j.get("status") in ["FF", "P"]:
692
+ return list(int(p) for p, _ in j.get("factors"))
693
+
694
+ factor_cache.get_external = get_external
695
+
696
+ Be aware that writing this code will trigger internet access
697
+ to factordb.com when calling ``factorint``.
698
+
699
+ """
700
+ def __init__(self, maxsize: int | None = None):
701
+ self._cache: OrderedDict[int, int] = OrderedDict()
702
+ self.maxsize = maxsize
703
+
704
+ def __len__(self) -> int:
705
+ return len(self._cache)
706
+
707
+ def __contains__(self, n) -> bool:
708
+ return n in self._cache
709
+
710
+ def __getitem__(self, n: int) -> int:
711
+ factor = self.get(n)
712
+ if factor is None:
713
+ raise KeyError(f"{n} does not exist.")
714
+ return factor
715
+
716
+ def __setitem__(self, n: int, factor: int):
717
+ if not (1 < factor <= n and n % factor == 0 and isprime(factor)):
718
+ raise ValueError(f"{factor} is not a prime factor of {n}")
719
+ self._cache[n] = max(self._cache.get(n, 0), factor)
720
+ if self.maxsize is not None and len(self._cache) > self.maxsize:
721
+ self._cache.popitem(False)
722
+
723
+ def __delitem__(self, n: int):
724
+ if n not in self._cache:
725
+ raise KeyError(f"{n} does not exist.")
726
+ del self._cache[n]
727
+
728
+ def __iter__(self):
729
+ return self._cache.__iter__()
730
+
731
+ def cache_clear(self) -> None:
732
+ """ Clear the cache """
733
+ self._cache = OrderedDict()
734
+
735
+ @property
736
+ def maxsize(self) -> int | None:
737
+ """ Returns the maximum cache size; if ``None``, it is unlimited. """
738
+ return self._maxsize
739
+
740
+ @maxsize.setter
741
+ def maxsize(self, value: int | None) -> None:
742
+ if value is not None and value <= 0:
743
+ raise ValueError("maxsize must be None or a non-negative integer.")
744
+ self._maxsize = value
745
+ if value is not None:
746
+ while len(self._cache) > value:
747
+ self._cache.popitem(False)
748
+
749
+ def get(self, n: int, default=None):
750
+ """ Return the prime factor of ``n``.
751
+ If it does not exist in the cache, return the value of ``default``.
752
+ """
753
+ if n <= sieve._list[-1]:
754
+ if sieve._list[bisect_left(sieve._list, n)] == n:
755
+ return n
756
+ if n in self._cache:
757
+ self._cache.move_to_end(n)
758
+ return self._cache[n]
759
+ if factors := self.get_external(n):
760
+ self.add(n, factors)
761
+ return self._cache[n]
762
+ return default
763
+
764
+ def add(self, n: int, factors: list[int]) -> None:
765
+ for p in sorted(factors, reverse=True):
766
+ self[n] = p
767
+ n, _ = remove(n, p)
768
+
769
+ def get_external(self, n: int) -> list[int] | None:
770
+ return None
771
+
772
+
773
+ factor_cache = FactorCache(maxsize=1000)
774
+
775
+
776
+ def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
777
+ r"""
778
+ Use Pollard's rho method to try to extract a nontrivial factor
779
+ of ``n``. The returned factor may be a composite number. If no
780
+ factor is found, ``None`` is returned.
781
+
782
+ The algorithm generates pseudo-random values of x with a generator
783
+ function, replacing x with F(x). If F is not supplied then the
784
+ function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
785
+ Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
786
+ supplied; the ``a`` will be ignored if F was supplied.
787
+
788
+ The sequence of numbers generated by such functions generally have a
789
+ a lead-up to some number and then loop around back to that number and
790
+ begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
791
+ and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
792
+
793
+ For a given function, very different leader-loop values can be obtained
794
+ so it is a good idea to allow for retries:
795
+
796
+ >>> from sympy.ntheory.generate import cycle_length
797
+ >>> n = 16843009
798
+ >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
799
+ >>> for s in range(5):
800
+ ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
801
+ ...
802
+ loop length = 2489; leader length = 43
803
+ loop length = 78; leader length = 121
804
+ loop length = 1482; leader length = 100
805
+ loop length = 1482; leader length = 286
806
+ loop length = 1482; leader length = 101
807
+
808
+ Here is an explicit example where there is a three element leadup to
809
+ a sequence of 3 numbers (11, 14, 4) that then repeat:
810
+
811
+ >>> x=2
812
+ >>> for i in range(9):
813
+ ... print(x)
814
+ ... x=(x**2+12)%17
815
+ ...
816
+ 2
817
+ 16
818
+ 13
819
+ 11
820
+ 14
821
+ 4
822
+ 11
823
+ 14
824
+ 4
825
+ >>> next(cycle_length(lambda x: (x**2+12)%17, 2))
826
+ (3, 3)
827
+ >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
828
+ [2, 16, 13, 11, 14, 4]
829
+
830
+ Instead of checking the differences of all generated values for a gcd
831
+ with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
832
+ 2nd and 4th, 3rd and 6th until it has been detected that the loop has been
833
+ traversed. Loops may be many thousands of steps long before rho finds a
834
+ factor or reports failure. If ``max_steps`` is specified, the iteration
835
+ is cancelled with a failure after the specified number of steps.
836
+
837
+ Examples
838
+ ========
839
+
840
+ >>> from sympy import pollard_rho
841
+ >>> n=16843009
842
+ >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
843
+ >>> pollard_rho(n, F=F)
844
+ 257
845
+
846
+ Use the default setting with a bad value of ``a`` and no retries:
847
+
848
+ >>> pollard_rho(n, a=n-2, retries=0)
849
+
850
+ If retries is > 0 then perhaps the problem will correct itself when
851
+ new values are generated for a:
852
+
853
+ >>> pollard_rho(n, a=n-2, retries=1)
854
+ 257
855
+
856
+ References
857
+ ==========
858
+
859
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
860
+ A Computational Perspective", Springer, 2nd edition, 229-231
861
+
862
+ """
863
+ n = int(n)
864
+ if n < 5:
865
+ raise ValueError('pollard_rho should receive n > 4')
866
+ randint = _randint(seed + retries)
867
+ V = s
868
+ for i in range(retries + 1):
869
+ U = V
870
+ if not F:
871
+ F = lambda x: (pow(x, 2, n) + a) % n
872
+ j = 0
873
+ while 1:
874
+ if max_steps and (j > max_steps):
875
+ break
876
+ j += 1
877
+ U = F(U)
878
+ V = F(F(V)) # V is 2x further along than U
879
+ g = gcd(U - V, n)
880
+ if g == 1:
881
+ continue
882
+ if g == n:
883
+ break
884
+ return int(g)
885
+ V = randint(0, n - 1)
886
+ a = randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
887
+ F = None
888
+ return None
889
+
890
+
891
+ def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
892
+ """
893
+ Use Pollard's p-1 method to try to extract a nontrivial factor
894
+ of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
895
+
896
+ The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
897
+ The default is 2. If ``retries`` > 0 then if no factor is found after the
898
+ first attempt, a new ``a`` will be generated randomly (using the ``seed``)
899
+ and the process repeated.
900
+
901
+ Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
902
+
903
+ A search is made for factors next to even numbers having a power smoothness
904
+ less than ``B``. Choosing a larger B increases the likelihood of finding a
905
+ larger factor but takes longer. Whether a factor of n is found or not
906
+ depends on ``a`` and the power smoothness of the even number just less than
907
+ the factor p (hence the name p - 1).
908
+
909
+ Although some discussion of what constitutes a good ``a`` some
910
+ descriptions are hard to interpret. At the modular.math site referenced
911
+ below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
912
+ for every prime power divisor of N. But consider the following:
913
+
914
+ >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
915
+ >>> n=257*1009
916
+ >>> smoothness_p(n)
917
+ (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
918
+
919
+ So we should (and can) find a root with B=16:
920
+
921
+ >>> pollard_pm1(n, B=16, a=3)
922
+ 1009
923
+
924
+ If we attempt to increase B to 256 we find that it does not work:
925
+
926
+ >>> pollard_pm1(n, B=256)
927
+ >>>
928
+
929
+ But if the value of ``a`` is changed we find that only multiples of
930
+ 257 work, e.g.:
931
+
932
+ >>> pollard_pm1(n, B=256, a=257)
933
+ 1009
934
+
935
+ Checking different ``a`` values shows that all the ones that did not
936
+ work had a gcd value not equal to ``n`` but equal to one of the
937
+ factors:
938
+
939
+ >>> from sympy import ilcm, igcd, factorint, Pow
940
+ >>> M = 1
941
+ >>> for i in range(2, 256):
942
+ ... M = ilcm(M, i)
943
+ ...
944
+ >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
945
+ ... igcd(pow(a, M, n) - 1, n) != n])
946
+ {1009}
947
+
948
+ But does aM % d for every divisor of n give 1?
949
+
950
+ >>> aM = pow(255, M, n)
951
+ >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
952
+ [(257**1, 1), (1009**1, 1)]
953
+
954
+ No, only one of them. So perhaps the principle is that a root will
955
+ be found for a given value of B provided that:
956
+
957
+ 1) the power smoothness of the p - 1 value next to the root
958
+ does not exceed B
959
+ 2) a**M % p != 1 for any of the divisors of n.
960
+
961
+ By trying more than one ``a`` it is possible that one of them
962
+ will yield a factor.
963
+
964
+ Examples
965
+ ========
966
+
967
+ With the default smoothness bound, this number cannot be cracked:
968
+
969
+ >>> from sympy.ntheory import pollard_pm1
970
+ >>> pollard_pm1(21477639576571)
971
+
972
+ Increasing the smoothness bound helps:
973
+
974
+ >>> pollard_pm1(21477639576571, B=2000)
975
+ 4410317
976
+
977
+ Looking at the smoothness of the factors of this number we find:
978
+
979
+ >>> from sympy.ntheory.factor_ import smoothness_p, factorint
980
+ >>> print(smoothness_p(21477639576571, visual=1))
981
+ p**i=4410317**1 has p-1 B=1787, B-pow=1787
982
+ p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
983
+
984
+ The B and B-pow are the same for the p - 1 factorizations of the divisors
985
+ because those factorizations had a very large prime factor:
986
+
987
+ >>> factorint(4410317 - 1)
988
+ {2: 2, 617: 1, 1787: 1}
989
+ >>> factorint(4869863-1)
990
+ {2: 1, 2434931: 1}
991
+
992
+ Note that until B reaches the B-pow value of 1787, the number is not cracked;
993
+
994
+ >>> pollard_pm1(21477639576571, B=1786)
995
+ >>> pollard_pm1(21477639576571, B=1787)
996
+ 4410317
997
+
998
+ The B value has to do with the factors of the number next to the divisor,
999
+ not the divisors themselves. A worst case scenario is that the number next
1000
+ to the factor p has a large prime divisisor or is a perfect power. If these
1001
+ conditions apply then the power-smoothness will be about p/2 or p. The more
1002
+ realistic is that there will be a large prime factor next to p requiring
1003
+ a B value on the order of p/2. Although primes may have been searched for
1004
+ up to this level, the p/2 is a factor of p - 1, something that we do not
1005
+ know. The modular.math reference below states that 15% of numbers in the
1006
+ range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
1007
+ will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
1008
+ percentages are nearly reversed...but in that range the simple trial
1009
+ division is quite fast.
1010
+
1011
+ References
1012
+ ==========
1013
+
1014
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
1015
+ A Computational Perspective", Springer, 2nd edition, 236-238
1016
+ .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
1017
+ .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
1018
+ """
1019
+
1020
+ n = int(n)
1021
+ if n < 4 or B < 3:
1022
+ raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
1023
+ randint = _randint(seed + B)
1024
+
1025
+ # computing a**lcm(1,2,3,..B) % n for B > 2
1026
+ # it looks weird, but it's right: primes run [2, B]
1027
+ # and the answer's not right until the loop is done.
1028
+ for i in range(retries + 1):
1029
+ aM = a
1030
+ for p in sieve.primerange(2, B + 1):
1031
+ e = int(math.log(B, p))
1032
+ aM = pow(aM, pow(p, e), n)
1033
+ g = gcd(aM - 1, n)
1034
+ if 1 < g < n:
1035
+ return int(g)
1036
+
1037
+ # get a new a:
1038
+ # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
1039
+ # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
1040
+ # give a zero, too, so we set the range as [2, n-2]. Some references
1041
+ # say 'a' should be coprime to n, but either will detect factors.
1042
+ a = randint(2, n - 2)
1043
+
1044
+
1045
+ def _trial(factors, n, candidates, verbose=False):
1046
+ """
1047
+ Helper function for integer factorization. Trial factors ``n`
1048
+ against all integers given in the sequence ``candidates``
1049
+ and updates the dict ``factors`` in-place. Returns the reduced
1050
+ value of ``n`` and a flag indicating whether any factors were found.
1051
+ """
1052
+ if verbose:
1053
+ factors0 = list(factors.keys())
1054
+ nfactors = len(factors)
1055
+ for d in candidates:
1056
+ if n % d == 0:
1057
+ if n != d:
1058
+ factor_cache[n] = d
1059
+ n, m = remove(n // d, d)
1060
+ factors[d] = m + 1
1061
+ if verbose:
1062
+ for k in sorted(set(factors).difference(set(factors0))):
1063
+ print(factor_msg % (k, factors[k]))
1064
+ return int(n), len(factors) != nfactors
1065
+
1066
+
1067
+ def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
1068
+ verbose, next_p):
1069
+ """
1070
+ Helper function for integer factorization. Checks if ``n``
1071
+ is a prime or a perfect power, and in those cases updates the factorization.
1072
+ """
1073
+ if verbose:
1074
+ print('Check for termination')
1075
+ if n == 1:
1076
+ if verbose:
1077
+ print(complete_msg)
1078
+ return True
1079
+ if n < next_p**2 or isprime(n):
1080
+ factor_cache[n] = n
1081
+ factors[int(n)] = 1
1082
+ if verbose:
1083
+ print(complete_msg)
1084
+ return True
1085
+
1086
+ # since we've already been factoring there is no need to do
1087
+ # simultaneous factoring with the power check
1088
+ p = _perfect_power(n, next_p)
1089
+ if not p:
1090
+ return False
1091
+ base, exp = p
1092
+ if base < next_p**2 or isprime(base):
1093
+ factor_cache[n] = base
1094
+ factors[base] = exp
1095
+ else:
1096
+ facs = factorint(base, limit, use_trial, use_rho, use_pm1,
1097
+ verbose=False)
1098
+ for b, e in facs.items():
1099
+ if verbose:
1100
+ print(factor_msg % (b, e))
1101
+ factors[b] = exp*e
1102
+ if verbose:
1103
+ print(complete_msg)
1104
+ return True
1105
+
1106
+
1107
+ trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
1108
+ trial_msg = "Trial division with primes [%i ... %i]"
1109
+ rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
1110
+ pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
1111
+ ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
1112
+ factor_msg = '\t%i ** %i'
1113
+ fermat_msg = 'Close factors satisfying Fermat condition found.'
1114
+ complete_msg = 'Factorization is complete.'
1115
+
1116
+
1117
+ def _factorint_small(factors, n, limit, fail_max, next_p=2):
1118
+ """
1119
+ Return the value of n and either a 0 (indicating that factorization up
1120
+ to the limit was complete) or else the next near-prime that would have
1121
+ been tested.
1122
+
1123
+ Factoring stops if there are fail_max unsuccessful tests in a row.
1124
+
1125
+ If factors of n were found they will be in the factors dictionary as
1126
+ {factor: multiplicity} and the returned value of n will have had those
1127
+ factors removed. The factors dictionary is modified in-place.
1128
+
1129
+ """
1130
+
1131
+ def done(n, d):
1132
+ """return n, d if the sqrt(n) was not reached yet, else
1133
+ n, 0 indicating that factoring is done.
1134
+ """
1135
+ if d*d <= n:
1136
+ return n, d
1137
+ return n, 0
1138
+
1139
+ limit2 = limit**2
1140
+ threshold2 = min(n, limit2)
1141
+
1142
+ if next_p < 3:
1143
+ if not n & 1:
1144
+ m = bit_scan1(n)
1145
+ factors[2] = m
1146
+ n >>= m
1147
+ threshold2 = min(n, limit2)
1148
+ next_p = 3
1149
+ if threshold2 < 9: # next_p**2 = 9
1150
+ return done(n, next_p)
1151
+
1152
+ if next_p < 5:
1153
+ if not n % 3:
1154
+ n //= 3
1155
+ m = 1
1156
+ while not n % 3:
1157
+ n //= 3
1158
+ m += 1
1159
+ if m == 20:
1160
+ n, mm = remove(n, 3)
1161
+ m += mm
1162
+ break
1163
+ factors[3] = m
1164
+ threshold2 = min(n, limit2)
1165
+ next_p = 5
1166
+ if threshold2 < 25: # next_p**2 = 25
1167
+ return done(n, next_p)
1168
+
1169
+ # Because of the order of checks, starting from `min_p = 6k+5`,
1170
+ # useless checks are caused.
1171
+ # We want to calculate
1172
+ # next_p += [-1, -2, 3, 2, 1, 0][next_p % 6]
1173
+ p6 = next_p % 6
1174
+ next_p += (-1 if p6 < 2 else 5) - p6
1175
+
1176
+ fails = 0
1177
+ while fails < fail_max:
1178
+ # next_p % 6 == 5
1179
+ if n % next_p:
1180
+ fails += 1
1181
+ else:
1182
+ n //= next_p
1183
+ m = 1
1184
+ while not n % next_p:
1185
+ n //= next_p
1186
+ m += 1
1187
+ if m == 20:
1188
+ n, mm = remove(n, next_p)
1189
+ m += mm
1190
+ break
1191
+ factors[next_p] = m
1192
+ fails = 0
1193
+ threshold2 = min(n, limit2)
1194
+ next_p += 2
1195
+ if threshold2 < next_p**2:
1196
+ return done(n, next_p)
1197
+
1198
+ # next_p % 6 == 1
1199
+ if n % next_p:
1200
+ fails += 1
1201
+ else:
1202
+ n //= next_p
1203
+ m = 1
1204
+ while not n % next_p:
1205
+ n //= next_p
1206
+ m += 1
1207
+ if m == 20:
1208
+ n, mm = remove(n, next_p)
1209
+ m += mm
1210
+ break
1211
+ factors[next_p] = m
1212
+ fails = 0
1213
+ threshold2 = min(n, limit2)
1214
+ next_p += 4
1215
+ if threshold2 < next_p**2:
1216
+ return done(n, next_p)
1217
+ return done(n, next_p)
1218
+
1219
+
1220
+ def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
1221
+ use_ecm=True, verbose=False, visual=None, multiple=False):
1222
+ r"""
1223
+ Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
1224
+ the prime factors of ``n`` as keys and their respective multiplicities
1225
+ as values. For example:
1226
+
1227
+ >>> from sympy.ntheory import factorint
1228
+ >>> factorint(2000) # 2000 = (2**4) * (5**3)
1229
+ {2: 4, 5: 3}
1230
+ >>> factorint(65537) # This number is prime
1231
+ {65537: 1}
1232
+
1233
+ For input less than 2, factorint behaves as follows:
1234
+
1235
+ - ``factorint(1)`` returns the empty factorization, ``{}``
1236
+ - ``factorint(0)`` returns ``{0:1}``
1237
+ - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
1238
+
1239
+ Partial Factorization:
1240
+
1241
+ If ``limit`` (> 3) is specified, the search is stopped after performing
1242
+ trial division up to (and including) the limit (or taking a
1243
+ corresponding number of rho/p-1 steps). This is useful if one has
1244
+ a large number and only is interested in finding small factors (if
1245
+ any). Note that setting a limit does not prevent larger factors
1246
+ from being found early; it simply means that the largest factor may
1247
+ be composite. Since checking for perfect power is relatively cheap, it is
1248
+ done regardless of the limit setting.
1249
+
1250
+ This number, for example, has two small factors and a huge
1251
+ semi-prime factor that cannot be reduced easily:
1252
+
1253
+ >>> from sympy.ntheory import isprime
1254
+ >>> a = 1407633717262338957430697921446883
1255
+ >>> f = factorint(a, limit=10000)
1256
+ >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
1257
+ True
1258
+ >>> isprime(max(f))
1259
+ False
1260
+
1261
+ This number has a small factor and a residual perfect power whose
1262
+ base is greater than the limit:
1263
+
1264
+ >>> factorint(3*101**7, limit=5)
1265
+ {3: 1, 101: 7}
1266
+
1267
+ List of Factors:
1268
+
1269
+ If ``multiple`` is set to ``True`` then a list containing the
1270
+ prime factors including multiplicities is returned.
1271
+
1272
+ >>> factorint(24, multiple=True)
1273
+ [2, 2, 2, 3]
1274
+
1275
+ Visual Factorization:
1276
+
1277
+ If ``visual`` is set to ``True``, then it will return a visual
1278
+ factorization of the integer. For example:
1279
+
1280
+ >>> from sympy import pprint
1281
+ >>> pprint(factorint(4200, visual=True))
1282
+ 3 1 2 1
1283
+ 2 *3 *5 *7
1284
+
1285
+ Note that this is achieved by using the evaluate=False flag in Mul
1286
+ and Pow. If you do other manipulations with an expression where
1287
+ evaluate=False, it may evaluate. Therefore, you should use the
1288
+ visual option only for visualization, and use the normal dictionary
1289
+ returned by visual=False if you want to perform operations on the
1290
+ factors.
1291
+
1292
+ You can easily switch between the two forms by sending them back to
1293
+ factorint:
1294
+
1295
+ >>> from sympy import Mul
1296
+ >>> regular = factorint(1764); regular
1297
+ {2: 2, 3: 2, 7: 2}
1298
+ >>> pprint(factorint(regular))
1299
+ 2 2 2
1300
+ 2 *3 *7
1301
+
1302
+ >>> visual = factorint(1764, visual=True); pprint(visual)
1303
+ 2 2 2
1304
+ 2 *3 *7
1305
+ >>> print(factorint(visual))
1306
+ {2: 2, 3: 2, 7: 2}
1307
+
1308
+ If you want to send a number to be factored in a partially factored form
1309
+ you can do so with a dictionary or unevaluated expression:
1310
+
1311
+ >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
1312
+ {2: 10, 3: 3}
1313
+ >>> factorint(Mul(4, 12, evaluate=False))
1314
+ {2: 4, 3: 1}
1315
+
1316
+ The table of the output logic is:
1317
+
1318
+ ====== ====== ======= =======
1319
+ Visual
1320
+ ------ ----------------------
1321
+ Input True False other
1322
+ ====== ====== ======= =======
1323
+ dict mul dict mul
1324
+ n mul dict dict
1325
+ mul mul dict dict
1326
+ ====== ====== ======= =======
1327
+
1328
+ Notes
1329
+ =====
1330
+
1331
+ Algorithm:
1332
+
1333
+ The function switches between multiple algorithms. Trial division
1334
+ quickly finds small factors (of the order 1-5 digits), and finds
1335
+ all large factors if given enough time. The Pollard rho and p-1
1336
+ algorithms are used to find large factors ahead of time; they
1337
+ will often find factors of the order of 10 digits within a few
1338
+ seconds:
1339
+
1340
+ >>> factors = factorint(12345678910111213141516)
1341
+ >>> for base, exp in sorted(factors.items()):
1342
+ ... print('%s %s' % (base, exp))
1343
+ ...
1344
+ 2 2
1345
+ 2507191691 1
1346
+ 1231026625769 1
1347
+
1348
+ Any of these methods can optionally be disabled with the following
1349
+ boolean parameters:
1350
+
1351
+ - ``use_trial``: Toggle use of trial division
1352
+ - ``use_rho``: Toggle use of Pollard's rho method
1353
+ - ``use_pm1``: Toggle use of Pollard's p-1 method
1354
+
1355
+ ``factorint`` also periodically checks if the remaining part is
1356
+ a prime number or a perfect power, and in those cases stops.
1357
+
1358
+ For unevaluated factorial, it uses Legendre's formula(theorem).
1359
+
1360
+
1361
+ If ``verbose`` is set to ``True``, detailed progress is printed.
1362
+
1363
+ See Also
1364
+ ========
1365
+
1366
+ smoothness, smoothness_p, divisors
1367
+
1368
+ """
1369
+ if isinstance(n, Dict):
1370
+ n = dict(n)
1371
+ if multiple:
1372
+ fac = factorint(n, limit=limit, use_trial=use_trial,
1373
+ use_rho=use_rho, use_pm1=use_pm1,
1374
+ verbose=verbose, visual=False, multiple=False)
1375
+ factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
1376
+ for p in sorted(fac)), [])
1377
+ return factorlist
1378
+
1379
+ factordict = {}
1380
+ if visual and not isinstance(n, (Mul, dict)):
1381
+ factordict = factorint(n, limit=limit, use_trial=use_trial,
1382
+ use_rho=use_rho, use_pm1=use_pm1,
1383
+ verbose=verbose, visual=False)
1384
+ elif isinstance(n, Mul):
1385
+ factordict = {int(k): int(v) for k, v in
1386
+ n.as_powers_dict().items()}
1387
+ elif isinstance(n, dict):
1388
+ factordict = n
1389
+ if factordict and isinstance(n, (Mul, dict)):
1390
+ # check it
1391
+ for key in list(factordict.keys()):
1392
+ if isprime(key):
1393
+ continue
1394
+ e = factordict.pop(key)
1395
+ d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
1396
+ use_pm1=use_pm1, verbose=verbose, visual=False)
1397
+ for k, v in d.items():
1398
+ if k in factordict:
1399
+ factordict[k] += v*e
1400
+ else:
1401
+ factordict[k] = v*e
1402
+ if visual or (type(n) is dict and
1403
+ visual is not True and
1404
+ visual is not False):
1405
+ if factordict == {}:
1406
+ return S.One
1407
+ if -1 in factordict:
1408
+ factordict.pop(-1)
1409
+ args = [S.NegativeOne]
1410
+ else:
1411
+ args = []
1412
+ args.extend([Pow(*i, evaluate=False)
1413
+ for i in sorted(factordict.items())])
1414
+ return Mul(*args, evaluate=False)
1415
+ elif isinstance(n, (dict, Mul)):
1416
+ return factordict
1417
+
1418
+ assert use_trial or use_rho or use_pm1 or use_ecm
1419
+
1420
+ from sympy.functions.combinatorial.factorials import factorial
1421
+ if isinstance(n, factorial):
1422
+ x = as_int(n.args[0])
1423
+ if x >= 20:
1424
+ factors = {}
1425
+ m = 2 # to initialize the if condition below
1426
+ for p in sieve.primerange(2, x + 1):
1427
+ if m > 1:
1428
+ m, q = 0, x // p
1429
+ while q != 0:
1430
+ m += q
1431
+ q //= p
1432
+ factors[p] = m
1433
+ if factors and verbose:
1434
+ for k in sorted(factors):
1435
+ print(factor_msg % (k, factors[k]))
1436
+ if verbose:
1437
+ print(complete_msg)
1438
+ return factors
1439
+ else:
1440
+ # if n < 20!, direct computation is faster
1441
+ # since it uses a lookup table
1442
+ n = n.func(x)
1443
+
1444
+ n = as_int(n)
1445
+ if limit:
1446
+ limit = int(limit)
1447
+ use_ecm = False
1448
+
1449
+ # special cases
1450
+ if n < 0:
1451
+ factors = factorint(
1452
+ -n, limit=limit, use_trial=use_trial, use_rho=use_rho,
1453
+ use_pm1=use_pm1, verbose=verbose, visual=False)
1454
+ factors[-1] = 1
1455
+ return factors
1456
+
1457
+ if limit and limit < 2:
1458
+ if n == 1:
1459
+ return {}
1460
+ return {n: 1}
1461
+ elif n < 10:
1462
+ # doing this we are assured of getting a limit > 2
1463
+ # when we have to compute it later
1464
+ return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
1465
+ {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
1466
+
1467
+ factors = {}
1468
+
1469
+ # do simplistic factorization
1470
+ if verbose:
1471
+ sn = str(n)
1472
+ if len(sn) > 50:
1473
+ print('Factoring %s' % sn[:5] + \
1474
+ '..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
1475
+ else:
1476
+ print('Factoring', n)
1477
+
1478
+ # this is the preliminary factorization for small factors
1479
+ # We want to guarantee that there are no small prime factors,
1480
+ # so we run even if `use_trial` is False.
1481
+ small = 2**15
1482
+ fail_max = 600
1483
+ small = min(small, limit or small)
1484
+ if verbose:
1485
+ print(trial_int_msg % (2, small, fail_max))
1486
+ n, next_p = _factorint_small(factors, n, small, fail_max)
1487
+ if factors and verbose:
1488
+ for k in sorted(factors):
1489
+ print(factor_msg % (k, factors[k]))
1490
+ if next_p == 0:
1491
+ if n > 1:
1492
+ factors[int(n)] = 1
1493
+ if verbose:
1494
+ print(complete_msg)
1495
+ return factors
1496
+ # Check if it exists in the cache
1497
+ while p := factor_cache.get(n):
1498
+ n, e = remove(n, p)
1499
+ factors[int(p)] = int(e)
1500
+ # first check if the simplistic run didn't finish
1501
+ # because of the limit and check for a perfect
1502
+ # power before exiting
1503
+ if limit and next_p > limit:
1504
+ if verbose:
1505
+ print('Exceeded limit:', limit)
1506
+ if _check_termination(factors, n, limit, use_trial,
1507
+ use_rho, use_pm1, verbose, next_p):
1508
+ return factors
1509
+ if n > 1:
1510
+ factors[int(n)] = 1
1511
+ return factors
1512
+ if _check_termination(factors, n, limit, use_trial,
1513
+ use_rho, use_pm1, verbose, next_p):
1514
+ return factors
1515
+
1516
+ # continue with more advanced factorization methods
1517
+ # ...do a Fermat test since it's so easy and we need the
1518
+ # square root anyway. Finding 2 factors is easy if they are
1519
+ # "close enough." This is the big root equivalent of dividing by
1520
+ # 2, 3, 5.
1521
+ sqrt_n = isqrt(n)
1522
+ a = sqrt_n + 1
1523
+ # If `n % 4 == 1`, `a` must be odd for `a**2 - n` to be a square number.
1524
+ if (n % 4 == 1) ^ (a & 1):
1525
+ a += 1
1526
+ a2 = a**2
1527
+ b2 = a2 - n
1528
+ for _ in range(3):
1529
+ b, fermat = sqrtrem(b2)
1530
+ if not fermat:
1531
+ if verbose:
1532
+ print(fermat_msg)
1533
+ for r in [a - b, a + b]:
1534
+ facs = factorint(r, limit=limit, use_trial=use_trial,
1535
+ use_rho=use_rho, use_pm1=use_pm1,
1536
+ verbose=verbose)
1537
+ for k, v in facs.items():
1538
+ factors[k] = factors.get(k, 0) + v
1539
+ factor_cache.add(n, facs)
1540
+ if verbose:
1541
+ print(complete_msg)
1542
+ return factors
1543
+ b2 += (a + 1) << 2 # equiv to (a + 2)**2 - n
1544
+ a += 2
1545
+
1546
+ # these are the limits for trial division which will
1547
+ # be attempted in parallel with pollard methods
1548
+ low, high = next_p, 2*next_p
1549
+
1550
+ # add 1 to make sure limit is reached in primerange calls
1551
+ _limit = (limit or sqrt_n) + 1
1552
+ iteration = 0
1553
+ while 1:
1554
+ high_ = min(high, _limit)
1555
+
1556
+ # Trial division
1557
+ if use_trial:
1558
+ if verbose:
1559
+ print(trial_msg % (low, high_))
1560
+ ps = sieve.primerange(low, high_)
1561
+ n, found_trial = _trial(factors, n, ps, verbose)
1562
+ next_p = high_
1563
+ if found_trial and _check_termination(factors, n, limit, use_trial,
1564
+ use_rho, use_pm1, verbose, next_p):
1565
+ return factors
1566
+ else:
1567
+ found_trial = False
1568
+
1569
+ if high > _limit:
1570
+ if verbose:
1571
+ print('Exceeded limit:', _limit)
1572
+ if n > 1:
1573
+ factors[int(n)] = 1
1574
+ if verbose:
1575
+ print(complete_msg)
1576
+ return factors
1577
+
1578
+ # Only used advanced methods when no small factors were found
1579
+ if not found_trial:
1580
+ # Pollard p-1
1581
+ if use_pm1:
1582
+ if verbose:
1583
+ print(pm1_msg % (low, high_))
1584
+ c = pollard_pm1(n, B=low, seed=high_)
1585
+ if c:
1586
+ if c < next_p**2 or isprime(c):
1587
+ ps = [c]
1588
+ else:
1589
+ ps = factorint(c, limit=limit,
1590
+ use_trial=use_trial,
1591
+ use_rho=use_rho,
1592
+ use_pm1=use_pm1,
1593
+ use_ecm=use_ecm,
1594
+ verbose=verbose)
1595
+ n, _ = _trial(factors, n, ps, verbose=False)
1596
+ if _check_termination(factors, n, limit, use_trial,
1597
+ use_rho, use_pm1, verbose, next_p):
1598
+ return factors
1599
+
1600
+ # Pollard rho
1601
+ if use_rho:
1602
+ if verbose:
1603
+ print(rho_msg % (1, low, high_))
1604
+ c = pollard_rho(n, retries=1, max_steps=low, seed=high_)
1605
+ if c:
1606
+ if c < next_p**2 or isprime(c):
1607
+ ps = [c]
1608
+ else:
1609
+ ps = factorint(c, limit=limit,
1610
+ use_trial=use_trial,
1611
+ use_rho=use_rho,
1612
+ use_pm1=use_pm1,
1613
+ use_ecm=use_ecm,
1614
+ verbose=verbose)
1615
+ n, _ = _trial(factors, n, ps, verbose=False)
1616
+ if _check_termination(factors, n, limit, use_trial,
1617
+ use_rho, use_pm1, verbose, next_p):
1618
+ return factors
1619
+ # Use subexponential algorithms if use_ecm
1620
+ # Use pollard algorithms for finding small factors for 3 iterations
1621
+ # if after small factors the number of digits of n >= 25 then use ecm
1622
+ iteration += 1
1623
+ if use_ecm and iteration >= 3 and num_digits(n) >= 24:
1624
+ break
1625
+ low, high = high, high*2
1626
+
1627
+ B1 = 10000
1628
+ B2 = 100*B1
1629
+ num_curves = 50
1630
+ while(1):
1631
+ if verbose:
1632
+ print(ecm_msg % (B1, B2, num_curves))
1633
+ factor = _ecm_one_factor(n, B1, B2, num_curves, seed=B1)
1634
+ if factor:
1635
+ if factor < next_p**2 or isprime(factor):
1636
+ ps = [factor]
1637
+ else:
1638
+ ps = factorint(factor, limit=limit,
1639
+ use_trial=use_trial,
1640
+ use_rho=use_rho,
1641
+ use_pm1=use_pm1,
1642
+ use_ecm=use_ecm,
1643
+ verbose=verbose)
1644
+ n, _ = _trial(factors, n, ps, verbose=False)
1645
+ if _check_termination(factors, n, limit, use_trial,
1646
+ use_rho, use_pm1, verbose, next_p):
1647
+ return factors
1648
+ B1 *= 5
1649
+ B2 = 100*B1
1650
+ num_curves *= 4
1651
+
1652
+
1653
+ def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
1654
+ verbose=False, visual=None, multiple=False):
1655
+ r"""
1656
+ Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
1657
+ the prime factors of ``r`` as keys and their respective multiplicities
1658
+ as values. For example:
1659
+
1660
+ >>> from sympy import factorrat, S
1661
+ >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
1662
+ {2: 3, 3: -2}
1663
+ >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
1664
+ {-1: 1, 3: -1, 7: -1, 47: -1}
1665
+
1666
+ Please see the docstring for ``factorint`` for detailed explanations
1667
+ and examples of the following keywords:
1668
+
1669
+ - ``limit``: Integer limit up to which trial division is done
1670
+ - ``use_trial``: Toggle use of trial division
1671
+ - ``use_rho``: Toggle use of Pollard's rho method
1672
+ - ``use_pm1``: Toggle use of Pollard's p-1 method
1673
+ - ``verbose``: Toggle detailed printing of progress
1674
+ - ``multiple``: Toggle returning a list of factors or dict
1675
+ - ``visual``: Toggle product form of output
1676
+ """
1677
+ if multiple:
1678
+ fac = factorrat(rat, limit=limit, use_trial=use_trial,
1679
+ use_rho=use_rho, use_pm1=use_pm1,
1680
+ verbose=verbose, visual=False, multiple=False)
1681
+ factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
1682
+ for p, _ in sorted(fac.items(),
1683
+ key=lambda elem: elem[0]
1684
+ if elem[1] > 0
1685
+ else 1/elem[0])), [])
1686
+ return factorlist
1687
+
1688
+ f = factorint(rat.p, limit=limit, use_trial=use_trial,
1689
+ use_rho=use_rho, use_pm1=use_pm1,
1690
+ verbose=verbose).copy()
1691
+ f = defaultdict(int, f)
1692
+ for p, e in factorint(rat.q, limit=limit,
1693
+ use_trial=use_trial,
1694
+ use_rho=use_rho,
1695
+ use_pm1=use_pm1,
1696
+ verbose=verbose).items():
1697
+ f[p] += -e
1698
+
1699
+ if len(f) > 1 and 1 in f:
1700
+ del f[1]
1701
+ if not visual:
1702
+ return dict(f)
1703
+ else:
1704
+ if -1 in f:
1705
+ f.pop(-1)
1706
+ args = [S.NegativeOne]
1707
+ else:
1708
+ args = []
1709
+ args.extend([Pow(*i, evaluate=False)
1710
+ for i in sorted(f.items())])
1711
+ return Mul(*args, evaluate=False)
1712
+
1713
+
1714
+ def primefactors(n, limit=None, verbose=False, **kwargs):
1715
+ """Return a sorted list of n's prime factors, ignoring multiplicity
1716
+ and any composite factor that remains if the limit was set too low
1717
+ for complete factorization. Unlike factorint(), primefactors() does
1718
+ not return -1 or 0.
1719
+
1720
+ Parameters
1721
+ ==========
1722
+
1723
+ n : integer
1724
+ limit, verbose, **kwargs :
1725
+ Additional keyword arguments to be passed to ``factorint``.
1726
+ Since ``kwargs`` is new in version 1.13,
1727
+ ``limit`` and ``verbose`` are retained for compatibility purposes.
1728
+
1729
+ Returns
1730
+ =======
1731
+
1732
+ list(int) : List of prime numbers dividing ``n``
1733
+
1734
+ Examples
1735
+ ========
1736
+
1737
+ >>> from sympy.ntheory import primefactors, factorint, isprime
1738
+ >>> primefactors(6)
1739
+ [2, 3]
1740
+ >>> primefactors(-5)
1741
+ [5]
1742
+
1743
+ >>> sorted(factorint(123456).items())
1744
+ [(2, 6), (3, 1), (643, 1)]
1745
+ >>> primefactors(123456)
1746
+ [2, 3, 643]
1747
+
1748
+ >>> sorted(factorint(10000000001, limit=200).items())
1749
+ [(101, 1), (99009901, 1)]
1750
+ >>> isprime(99009901)
1751
+ False
1752
+ >>> primefactors(10000000001, limit=300)
1753
+ [101]
1754
+
1755
+ See Also
1756
+ ========
1757
+
1758
+ factorint, divisors
1759
+
1760
+ """
1761
+ n = int(n)
1762
+ kwargs.update({"visual": None, "multiple": False,
1763
+ "limit": limit, "verbose": verbose})
1764
+ factors = sorted(factorint(n=n, **kwargs).keys())
1765
+ # We want to calculate
1766
+ # s = [f for f in factors if isprime(f)]
1767
+ s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
1768
+ if factors and isprime(factors[-1]):
1769
+ s += [factors[-1]]
1770
+ return s
1771
+
1772
+
1773
+ def _divisors(n, proper=False):
1774
+ """Helper function for divisors which generates the divisors.
1775
+
1776
+ Parameters
1777
+ ==========
1778
+
1779
+ n : int
1780
+ a nonnegative integer
1781
+ proper: bool
1782
+ If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).
1783
+
1784
+ """
1785
+ if n <= 1:
1786
+ if not proper and n:
1787
+ yield 1
1788
+ return
1789
+
1790
+ factordict = factorint(n)
1791
+ ps = sorted(factordict.keys())
1792
+
1793
+ def rec_gen(n=0):
1794
+ if n == len(ps):
1795
+ yield 1
1796
+ else:
1797
+ pows = [1]
1798
+ for _ in range(factordict[ps[n]]):
1799
+ pows.append(pows[-1] * ps[n])
1800
+ yield from (p * q for q in rec_gen(n + 1) for p in pows)
1801
+
1802
+ if proper:
1803
+ yield from (p for p in rec_gen() if p != n)
1804
+ else:
1805
+ yield from rec_gen()
1806
+
1807
+
1808
+ def divisors(n, generator=False, proper=False):
1809
+ r"""
1810
+ Return all divisors of n sorted from 1..n by default.
1811
+ If generator is ``True`` an unordered generator is returned.
1812
+
1813
+ The number of divisors of n can be quite large if there are many
1814
+ prime factors (counting repeated factors). If only the number of
1815
+ factors is desired use divisor_count(n).
1816
+
1817
+ Examples
1818
+ ========
1819
+
1820
+ >>> from sympy import divisors, divisor_count
1821
+ >>> divisors(24)
1822
+ [1, 2, 3, 4, 6, 8, 12, 24]
1823
+ >>> divisor_count(24)
1824
+ 8
1825
+
1826
+ >>> list(divisors(120, generator=True))
1827
+ [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
1828
+
1829
+ Notes
1830
+ =====
1831
+
1832
+ This is a slightly modified version of Tim Peters referenced at:
1833
+ https://stackoverflow.com/questions/1010381/python-factorization
1834
+
1835
+ See Also
1836
+ ========
1837
+
1838
+ primefactors, factorint, divisor_count
1839
+ """
1840
+ rv = _divisors(as_int(abs(n)), proper)
1841
+ return rv if generator else sorted(rv)
1842
+
1843
+
1844
+ def divisor_count(n, modulus=1, proper=False):
1845
+ """
1846
+ Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
1847
+ those that are divisible by ``modulus`` are counted. If ``proper`` is True
1848
+ then the divisor of ``n`` will not be counted.
1849
+
1850
+ Examples
1851
+ ========
1852
+
1853
+ >>> from sympy import divisor_count
1854
+ >>> divisor_count(6)
1855
+ 4
1856
+ >>> divisor_count(6, 2)
1857
+ 2
1858
+ >>> divisor_count(6, proper=True)
1859
+ 3
1860
+
1861
+ See Also
1862
+ ========
1863
+
1864
+ factorint, divisors, totient, proper_divisor_count
1865
+
1866
+ """
1867
+
1868
+ if not modulus:
1869
+ return 0
1870
+ elif modulus != 1:
1871
+ n, r = divmod(n, modulus)
1872
+ if r:
1873
+ return 0
1874
+ if n == 0:
1875
+ return 0
1876
+ n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
1877
+ if n and proper:
1878
+ n -= 1
1879
+ return n
1880
+
1881
+
1882
+ def proper_divisors(n, generator=False):
1883
+ """
1884
+ Return all divisors of n except n, sorted by default.
1885
+ If generator is ``True`` an unordered generator is returned.
1886
+
1887
+ Examples
1888
+ ========
1889
+
1890
+ >>> from sympy import proper_divisors, proper_divisor_count
1891
+ >>> proper_divisors(24)
1892
+ [1, 2, 3, 4, 6, 8, 12]
1893
+ >>> proper_divisor_count(24)
1894
+ 7
1895
+ >>> list(proper_divisors(120, generator=True))
1896
+ [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
1897
+
1898
+ See Also
1899
+ ========
1900
+
1901
+ factorint, divisors, proper_divisor_count
1902
+
1903
+ """
1904
+ return divisors(n, generator=generator, proper=True)
1905
+
1906
+
1907
+ def proper_divisor_count(n, modulus=1):
1908
+ """
1909
+ Return the number of proper divisors of ``n``.
1910
+
1911
+ Examples
1912
+ ========
1913
+
1914
+ >>> from sympy import proper_divisor_count
1915
+ >>> proper_divisor_count(6)
1916
+ 3
1917
+ >>> proper_divisor_count(6, modulus=2)
1918
+ 1
1919
+
1920
+ See Also
1921
+ ========
1922
+
1923
+ divisors, proper_divisors, divisor_count
1924
+
1925
+ """
1926
+ return divisor_count(n, modulus=modulus, proper=True)
1927
+
1928
+
1929
+ def _udivisors(n):
1930
+ """Helper function for udivisors which generates the unitary divisors.
1931
+
1932
+ Parameters
1933
+ ==========
1934
+
1935
+ n : int
1936
+ a nonnegative integer
1937
+
1938
+ """
1939
+ if n <= 1:
1940
+ if n == 1:
1941
+ yield 1
1942
+ return
1943
+
1944
+ factorpows = [p**e for p, e in factorint(n).items()]
1945
+ # We want to calculate
1946
+ # yield from (math.prod(s) for s in powersets(factorpows))
1947
+ for i in range(2**len(factorpows)):
1948
+ d = 1
1949
+ for k in range(i.bit_length()):
1950
+ if i & 1:
1951
+ d *= factorpows[k]
1952
+ i >>= 1
1953
+ yield d
1954
+
1955
+
1956
+ def udivisors(n, generator=False):
1957
+ r"""
1958
+ Return all unitary divisors of n sorted from 1..n by default.
1959
+ If generator is ``True`` an unordered generator is returned.
1960
+
1961
+ The number of unitary divisors of n can be quite large if there are many
1962
+ prime factors. If only the number of unitary divisors is desired use
1963
+ udivisor_count(n).
1964
+
1965
+ Examples
1966
+ ========
1967
+
1968
+ >>> from sympy.ntheory.factor_ import udivisors, udivisor_count
1969
+ >>> udivisors(15)
1970
+ [1, 3, 5, 15]
1971
+ >>> udivisor_count(15)
1972
+ 4
1973
+
1974
+ >>> sorted(udivisors(120, generator=True))
1975
+ [1, 3, 5, 8, 15, 24, 40, 120]
1976
+
1977
+ See Also
1978
+ ========
1979
+
1980
+ primefactors, factorint, divisors, divisor_count, udivisor_count
1981
+
1982
+ References
1983
+ ==========
1984
+
1985
+ .. [1] https://en.wikipedia.org/wiki/Unitary_divisor
1986
+ .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
1987
+
1988
+ """
1989
+ rv = _udivisors(as_int(abs(n)))
1990
+ return rv if generator else sorted(rv)
1991
+
1992
+
1993
+ def udivisor_count(n):
1994
+ """
1995
+ Return the number of unitary divisors of ``n``.
1996
+
1997
+ Parameters
1998
+ ==========
1999
+
2000
+ n : integer
2001
+
2002
+ Examples
2003
+ ========
2004
+
2005
+ >>> from sympy.ntheory.factor_ import udivisor_count
2006
+ >>> udivisor_count(120)
2007
+ 8
2008
+
2009
+ See Also
2010
+ ========
2011
+
2012
+ factorint, divisors, udivisors, divisor_count, totient
2013
+
2014
+ References
2015
+ ==========
2016
+
2017
+ .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
2018
+
2019
+ """
2020
+
2021
+ if n == 0:
2022
+ return 0
2023
+ return 2**len([p for p in factorint(n) if p > 1])
2024
+
2025
+
2026
+ def _antidivisors(n):
2027
+ """Helper function for antidivisors which generates the antidivisors.
2028
+
2029
+ Parameters
2030
+ ==========
2031
+
2032
+ n : int
2033
+ a nonnegative integer
2034
+
2035
+ """
2036
+ if n <= 2:
2037
+ return
2038
+ for d in _divisors(n):
2039
+ y = 2*d
2040
+ if n > y and n % y:
2041
+ yield y
2042
+ for d in _divisors(2*n-1):
2043
+ if n > d >= 2 and n % d:
2044
+ yield d
2045
+ for d in _divisors(2*n+1):
2046
+ if n > d >= 2 and n % d:
2047
+ yield d
2048
+
2049
+
2050
+ def antidivisors(n, generator=False):
2051
+ r"""
2052
+ Return all antidivisors of n sorted from 1..n by default.
2053
+
2054
+ Antidivisors [1]_ of n are numbers that do not divide n by the largest
2055
+ possible margin. If generator is True an unordered generator is returned.
2056
+
2057
+ Examples
2058
+ ========
2059
+
2060
+ >>> from sympy.ntheory.factor_ import antidivisors
2061
+ >>> antidivisors(24)
2062
+ [7, 16]
2063
+
2064
+ >>> sorted(antidivisors(128, generator=True))
2065
+ [3, 5, 15, 17, 51, 85]
2066
+
2067
+ See Also
2068
+ ========
2069
+
2070
+ primefactors, factorint, divisors, divisor_count, antidivisor_count
2071
+
2072
+ References
2073
+ ==========
2074
+
2075
+ .. [1] definition is described in https://oeis.org/A066272/a066272a.html
2076
+
2077
+ """
2078
+ rv = _antidivisors(as_int(abs(n)))
2079
+ return rv if generator else sorted(rv)
2080
+
2081
+
2082
+ def antidivisor_count(n):
2083
+ """
2084
+ Return the number of antidivisors [1]_ of ``n``.
2085
+
2086
+ Parameters
2087
+ ==========
2088
+
2089
+ n : integer
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy.ntheory.factor_ import antidivisor_count
2095
+ >>> antidivisor_count(13)
2096
+ 4
2097
+ >>> antidivisor_count(27)
2098
+ 5
2099
+
2100
+ See Also
2101
+ ========
2102
+
2103
+ factorint, divisors, antidivisors, divisor_count, totient
2104
+
2105
+ References
2106
+ ==========
2107
+
2108
+ .. [1] formula from https://oeis.org/A066272
2109
+
2110
+ """
2111
+
2112
+ n = as_int(abs(n))
2113
+ if n <= 2:
2114
+ return 0
2115
+ return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
2116
+ divisor_count(n) - divisor_count(n, 2) - 5
2117
+
2118
+ @deprecated("""\
2119
+ The `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.""",
2120
+ deprecated_since_version="1.13",
2121
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2122
+ def totient(n):
2123
+ r"""
2124
+ Calculate the Euler totient function phi(n)
2125
+
2126
+ .. deprecated:: 1.13
2127
+
2128
+ The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
2129
+ instead. See its documentation for more information. See
2130
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2131
+
2132
+ ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
2133
+ that are relatively prime to n.
2134
+
2135
+ Parameters
2136
+ ==========
2137
+
2138
+ n : integer
2139
+
2140
+ Examples
2141
+ ========
2142
+
2143
+ >>> from sympy.functions.combinatorial.numbers import totient
2144
+ >>> totient(1)
2145
+ 1
2146
+ >>> totient(25)
2147
+ 20
2148
+ >>> totient(45) == totient(5)*totient(9)
2149
+ True
2150
+
2151
+ See Also
2152
+ ========
2153
+
2154
+ divisor_count
2155
+
2156
+ References
2157
+ ==========
2158
+
2159
+ .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
2160
+ .. [2] https://mathworld.wolfram.com/TotientFunction.html
2161
+
2162
+ """
2163
+ from sympy.functions.combinatorial.numbers import totient as _totient
2164
+ return _totient(n)
2165
+
2166
+
2167
+ @deprecated("""\
2168
+ The `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.""",
2169
+ deprecated_since_version="1.13",
2170
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2171
+ def reduced_totient(n):
2172
+ r"""
2173
+ Calculate the Carmichael reduced totient function lambda(n)
2174
+
2175
+ .. deprecated:: 1.13
2176
+
2177
+ The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
2178
+ instead. See its documentation for more information. See
2179
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2180
+
2181
+ ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
2182
+ `k^m \equiv 1 \mod n` for all k relatively prime to n.
2183
+
2184
+ Examples
2185
+ ========
2186
+
2187
+ >>> from sympy.functions.combinatorial.numbers import reduced_totient
2188
+ >>> reduced_totient(1)
2189
+ 1
2190
+ >>> reduced_totient(8)
2191
+ 2
2192
+ >>> reduced_totient(30)
2193
+ 4
2194
+
2195
+ See Also
2196
+ ========
2197
+
2198
+ totient
2199
+
2200
+ References
2201
+ ==========
2202
+
2203
+ .. [1] https://en.wikipedia.org/wiki/Carmichael_function
2204
+ .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
2205
+
2206
+ """
2207
+ from sympy.functions.combinatorial.numbers import reduced_totient as _reduced_totient
2208
+ return _reduced_totient(n)
2209
+
2210
+
2211
+ @deprecated("""\
2212
+ The `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.""",
2213
+ deprecated_since_version="1.13",
2214
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2215
+ def divisor_sigma(n, k=1):
2216
+ r"""
2217
+ Calculate the divisor function `\sigma_k(n)` for positive integer n
2218
+
2219
+ .. deprecated:: 1.13
2220
+
2221
+ The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
2222
+ instead. See its documentation for more information. See
2223
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2224
+
2225
+ ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
2226
+
2227
+ If n's prime factorization is:
2228
+
2229
+ .. math ::
2230
+ n = \prod_{i=1}^\omega p_i^{m_i},
2231
+
2232
+ then
2233
+
2234
+ .. math ::
2235
+ \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
2236
+ + p_i^{m_ik}).
2237
+
2238
+ Parameters
2239
+ ==========
2240
+
2241
+ n : integer
2242
+
2243
+ k : integer, optional
2244
+ power of divisors in the sum
2245
+
2246
+ for k = 0, 1:
2247
+ ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
2248
+ ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
2249
+
2250
+ Default for k is 1.
2251
+
2252
+ Examples
2253
+ ========
2254
+
2255
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2256
+ >>> divisor_sigma(18, 0)
2257
+ 6
2258
+ >>> divisor_sigma(39, 1)
2259
+ 56
2260
+ >>> divisor_sigma(12, 2)
2261
+ 210
2262
+ >>> divisor_sigma(37)
2263
+ 38
2264
+
2265
+ See Also
2266
+ ========
2267
+
2268
+ divisor_count, totient, divisors, factorint
2269
+
2270
+ References
2271
+ ==========
2272
+
2273
+ .. [1] https://en.wikipedia.org/wiki/Divisor_function
2274
+
2275
+ """
2276
+ from sympy.functions.combinatorial.numbers import divisor_sigma as func_divisor_sigma
2277
+ return func_divisor_sigma(n, k)
2278
+
2279
+
2280
+ def _divisor_sigma(n:int, k:int=1) -> int:
2281
+ r""" Calculate the divisor function `\sigma_k(n)` for positive integer n
2282
+
2283
+ Parameters
2284
+ ==========
2285
+
2286
+ n : int
2287
+ positive integer
2288
+ k : int
2289
+ nonnegative integer
2290
+
2291
+ See Also
2292
+ ========
2293
+
2294
+ sympy.functions.combinatorial.numbers.divisor_sigma
2295
+
2296
+ """
2297
+ if k == 0:
2298
+ return math.prod(e + 1 for e in factorint(n).values())
2299
+ return math.prod((p**(k*(e + 1)) - 1)//(p**k - 1) for p, e in factorint(n).items())
2300
+
2301
+
2302
+ def core(n, t=2):
2303
+ r"""
2304
+ Calculate core(n, t) = `core_t(n)` of a positive integer n
2305
+
2306
+ ``core_2(n)`` is equal to the squarefree part of n
2307
+
2308
+ If n's prime factorization is:
2309
+
2310
+ .. math ::
2311
+ n = \prod_{i=1}^\omega p_i^{m_i},
2312
+
2313
+ then
2314
+
2315
+ .. math ::
2316
+ core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
2317
+
2318
+ Parameters
2319
+ ==========
2320
+
2321
+ n : integer
2322
+
2323
+ t : integer
2324
+ core(n, t) calculates the t-th power free part of n
2325
+
2326
+ ``core(n, 2)`` is the squarefree part of ``n``
2327
+ ``core(n, 3)`` is the cubefree part of ``n``
2328
+
2329
+ Default for t is 2.
2330
+
2331
+ Examples
2332
+ ========
2333
+
2334
+ >>> from sympy.ntheory.factor_ import core
2335
+ >>> core(24, 2)
2336
+ 6
2337
+ >>> core(9424, 3)
2338
+ 1178
2339
+ >>> core(379238)
2340
+ 379238
2341
+ >>> core(15**11, 10)
2342
+ 15
2343
+
2344
+ See Also
2345
+ ========
2346
+
2347
+ factorint, sympy.solvers.diophantine.diophantine.square_factor
2348
+
2349
+ References
2350
+ ==========
2351
+
2352
+ .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
2353
+
2354
+ """
2355
+
2356
+ n = as_int(n)
2357
+ t = as_int(t)
2358
+ if n <= 0:
2359
+ raise ValueError("n must be a positive integer")
2360
+ elif t <= 1:
2361
+ raise ValueError("t must be >= 2")
2362
+ else:
2363
+ y = 1
2364
+ for p, e in factorint(n).items():
2365
+ y *= p**(e % t)
2366
+ return y
2367
+
2368
+
2369
+ @deprecated("""\
2370
+ The `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.""",
2371
+ deprecated_since_version="1.13",
2372
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2373
+ def udivisor_sigma(n, k=1):
2374
+ r"""
2375
+ Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
2376
+
2377
+ .. deprecated:: 1.13
2378
+
2379
+ The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
2380
+ instead. See its documentation for more information. See
2381
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2382
+
2383
+ ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
2384
+
2385
+ If n's prime factorization is:
2386
+
2387
+ .. math ::
2388
+ n = \prod_{i=1}^\omega p_i^{m_i},
2389
+
2390
+ then
2391
+
2392
+ .. math ::
2393
+ \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
2394
+
2395
+ Parameters
2396
+ ==========
2397
+
2398
+ k : power of divisors in the sum
2399
+
2400
+ for k = 0, 1:
2401
+ ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
2402
+ ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
2403
+
2404
+ Default for k is 1.
2405
+
2406
+ Examples
2407
+ ========
2408
+
2409
+ >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
2410
+ >>> udivisor_sigma(18, 0)
2411
+ 4
2412
+ >>> udivisor_sigma(74, 1)
2413
+ 114
2414
+ >>> udivisor_sigma(36, 3)
2415
+ 47450
2416
+ >>> udivisor_sigma(111)
2417
+ 152
2418
+
2419
+ See Also
2420
+ ========
2421
+
2422
+ divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
2423
+ factorint
2424
+
2425
+ References
2426
+ ==========
2427
+
2428
+ .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
2429
+
2430
+ """
2431
+ from sympy.functions.combinatorial.numbers import udivisor_sigma as _udivisor_sigma
2432
+ return _udivisor_sigma(n, k)
2433
+
2434
+
2435
+ @deprecated("""\
2436
+ The `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.""",
2437
+ deprecated_since_version="1.13",
2438
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2439
+ def primenu(n):
2440
+ r"""
2441
+ Calculate the number of distinct prime factors for a positive integer n.
2442
+
2443
+ .. deprecated:: 1.13
2444
+
2445
+ The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
2446
+ instead. See its documentation for more information. See
2447
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2448
+
2449
+ If n's prime factorization is:
2450
+
2451
+ .. math ::
2452
+ n = \prod_{i=1}^k p_i^{m_i},
2453
+
2454
+ then ``primenu(n)`` or `\nu(n)` is:
2455
+
2456
+ .. math ::
2457
+ \nu(n) = k.
2458
+
2459
+ Examples
2460
+ ========
2461
+
2462
+ >>> from sympy.functions.combinatorial.numbers import primenu
2463
+ >>> primenu(1)
2464
+ 0
2465
+ >>> primenu(30)
2466
+ 3
2467
+
2468
+ See Also
2469
+ ========
2470
+
2471
+ factorint
2472
+
2473
+ References
2474
+ ==========
2475
+
2476
+ .. [1] https://mathworld.wolfram.com/PrimeFactor.html
2477
+
2478
+ """
2479
+ from sympy.functions.combinatorial.numbers import primenu as _primenu
2480
+ return _primenu(n)
2481
+
2482
+
2483
+ @deprecated("""\
2484
+ The `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.""",
2485
+ deprecated_since_version="1.13",
2486
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
2487
+ def primeomega(n):
2488
+ r"""
2489
+ Calculate the number of prime factors counting multiplicities for a
2490
+ positive integer n.
2491
+
2492
+ .. deprecated:: 1.13
2493
+
2494
+ The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
2495
+ instead. See its documentation for more information. See
2496
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
2497
+
2498
+ If n's prime factorization is:
2499
+
2500
+ .. math ::
2501
+ n = \prod_{i=1}^k p_i^{m_i},
2502
+
2503
+ then ``primeomega(n)`` or `\Omega(n)` is:
2504
+
2505
+ .. math ::
2506
+ \Omega(n) = \sum_{i=1}^k m_i.
2507
+
2508
+ Examples
2509
+ ========
2510
+
2511
+ >>> from sympy.functions.combinatorial.numbers import primeomega
2512
+ >>> primeomega(1)
2513
+ 0
2514
+ >>> primeomega(20)
2515
+ 3
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ factorint
2521
+
2522
+ References
2523
+ ==========
2524
+
2525
+ .. [1] https://mathworld.wolfram.com/PrimeFactor.html
2526
+
2527
+ """
2528
+ from sympy.functions.combinatorial.numbers import primeomega as _primeomega
2529
+ return _primeomega(n)
2530
+
2531
+
2532
+ def mersenne_prime_exponent(nth):
2533
+ """Returns the exponent ``i`` for the nth Mersenne prime (which
2534
+ has the form `2^i - 1`).
2535
+
2536
+ Examples
2537
+ ========
2538
+
2539
+ >>> from sympy.ntheory.factor_ import mersenne_prime_exponent
2540
+ >>> mersenne_prime_exponent(1)
2541
+ 2
2542
+ >>> mersenne_prime_exponent(20)
2543
+ 4423
2544
+ """
2545
+ n = as_int(nth)
2546
+ if n < 1:
2547
+ raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
2548
+ if n > 51:
2549
+ raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
2550
+ return MERSENNE_PRIME_EXPONENTS[n - 1]
2551
+
2552
+
2553
+ def is_perfect(n):
2554
+ """Returns True if ``n`` is a perfect number, else False.
2555
+
2556
+ A perfect number is equal to the sum of its positive, proper divisors.
2557
+
2558
+ Examples
2559
+ ========
2560
+
2561
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2562
+ >>> from sympy.ntheory.factor_ import is_perfect, divisors
2563
+ >>> is_perfect(20)
2564
+ False
2565
+ >>> is_perfect(6)
2566
+ True
2567
+ >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
2568
+ True
2569
+
2570
+ References
2571
+ ==========
2572
+
2573
+ .. [1] https://mathworld.wolfram.com/PerfectNumber.html
2574
+ .. [2] https://en.wikipedia.org/wiki/Perfect_number
2575
+
2576
+ """
2577
+ n = as_int(n)
2578
+ if n < 1:
2579
+ return False
2580
+ if n % 2 == 0:
2581
+ m = (n.bit_length() + 1) >> 1
2582
+ if (1 << (m - 1)) * ((1 << m) - 1) != n:
2583
+ # Even perfect numbers must be of the form `2^{m-1}(2^m-1)`
2584
+ return False
2585
+ return m in MERSENNE_PRIME_EXPONENTS or is_mersenne_prime(2**m - 1)
2586
+
2587
+ # n is an odd integer
2588
+ if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/
2589
+ return False
2590
+ if n % 105 == 0: # not divis by 105
2591
+ return False
2592
+ if all(n % m != r for m, r in [(12, 1), (468, 117), (324, 81)]):
2593
+ return False
2594
+ # there are many criteria that the factor structure of n
2595
+ # must meet; since we will have to factor it to test the
2596
+ # structure we will have the factors and can then check
2597
+ # to see whether it is a perfect number or not. So we
2598
+ # skip the structure checks and go straight to the final
2599
+ # test below.
2600
+ result = abundance(n) == 0
2601
+ if result:
2602
+ raise ValueError(filldedent('''In 1888, Sylvester stated: "
2603
+ ...a prolonged meditation on the subject has satisfied
2604
+ me that the existence of any one such [odd perfect number]
2605
+ -- its escape, so to say, from the complex web of conditions
2606
+ which hem it in on all sides -- would be little short of a
2607
+ miracle." I guess SymPy just found that miracle and it
2608
+ factors like this: %s''' % factorint(n)))
2609
+ return result
2610
+
2611
+
2612
+ def abundance(n):
2613
+ """Returns the difference between the sum of the positive
2614
+ proper divisors of a number and the number.
2615
+
2616
+ Examples
2617
+ ========
2618
+
2619
+ >>> from sympy.ntheory import abundance, is_perfect, is_abundant
2620
+ >>> abundance(6)
2621
+ 0
2622
+ >>> is_perfect(6)
2623
+ True
2624
+ >>> abundance(10)
2625
+ -2
2626
+ >>> is_abundant(10)
2627
+ False
2628
+ """
2629
+ return _divisor_sigma(n) - 2 * n
2630
+
2631
+
2632
+ def is_abundant(n):
2633
+ """Returns True if ``n`` is an abundant number, else False.
2634
+
2635
+ A abundant number is smaller than the sum of its positive proper divisors.
2636
+
2637
+ Examples
2638
+ ========
2639
+
2640
+ >>> from sympy.ntheory.factor_ import is_abundant
2641
+ >>> is_abundant(20)
2642
+ True
2643
+ >>> is_abundant(15)
2644
+ False
2645
+
2646
+ References
2647
+ ==========
2648
+
2649
+ .. [1] https://mathworld.wolfram.com/AbundantNumber.html
2650
+
2651
+ """
2652
+ n = as_int(n)
2653
+ if is_perfect(n):
2654
+ return False
2655
+ return n % 6 == 0 or bool(abundance(n) > 0)
2656
+
2657
+
2658
+ def is_deficient(n):
2659
+ """Returns True if ``n`` is a deficient number, else False.
2660
+
2661
+ A deficient number is greater than the sum of its positive proper divisors.
2662
+
2663
+ Examples
2664
+ ========
2665
+
2666
+ >>> from sympy.ntheory.factor_ import is_deficient
2667
+ >>> is_deficient(20)
2668
+ False
2669
+ >>> is_deficient(15)
2670
+ True
2671
+
2672
+ References
2673
+ ==========
2674
+
2675
+ .. [1] https://mathworld.wolfram.com/DeficientNumber.html
2676
+
2677
+ """
2678
+ n = as_int(n)
2679
+ if is_perfect(n):
2680
+ return False
2681
+ return bool(abundance(n) < 0)
2682
+
2683
+
2684
+ def is_amicable(m, n):
2685
+ """Returns True if the numbers `m` and `n` are "amicable", else False.
2686
+
2687
+ Amicable numbers are two different numbers so related that the sum
2688
+ of the proper divisors of each is equal to that of the other.
2689
+
2690
+ Examples
2691
+ ========
2692
+
2693
+ >>> from sympy.functions.combinatorial.numbers import divisor_sigma
2694
+ >>> from sympy.ntheory.factor_ import is_amicable
2695
+ >>> is_amicable(220, 284)
2696
+ True
2697
+ >>> divisor_sigma(220) == divisor_sigma(284)
2698
+ True
2699
+
2700
+ References
2701
+ ==========
2702
+
2703
+ .. [1] https://en.wikipedia.org/wiki/Amicable_numbers
2704
+
2705
+ """
2706
+ return m != n and m + n == _divisor_sigma(m) == _divisor_sigma(n)
2707
+
2708
+
2709
+ def is_carmichael(n):
2710
+ """ Returns True if the numbers `n` is Carmichael number, else False.
2711
+
2712
+ Parameters
2713
+ ==========
2714
+
2715
+ n : Integer
2716
+
2717
+ References
2718
+ ==========
2719
+
2720
+ .. [1] https://en.wikipedia.org/wiki/Carmichael_number
2721
+ .. [2] https://oeis.org/A002997
2722
+
2723
+ """
2724
+ if n < 561:
2725
+ return False
2726
+ return n % 2 and not isprime(n) and \
2727
+ all(e == 1 and (n - 1) % (p - 1) == 0 for p, e in factorint(n).items())
2728
+
2729
+
2730
+ def find_carmichael_numbers_in_range(x, y):
2731
+ """ Returns a list of the number of Carmichael in the range
2732
+
2733
+ See Also
2734
+ ========
2735
+
2736
+ is_carmichael
2737
+
2738
+ """
2739
+ if 0 <= x <= y:
2740
+ if x % 2 == 0:
2741
+ return [i for i in range(x + 1, y, 2) if is_carmichael(i)]
2742
+ else:
2743
+ return [i for i in range(x, y, 2) if is_carmichael(i)]
2744
+ else:
2745
+ raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
2746
+
2747
+
2748
+ def find_first_n_carmichaels(n):
2749
+ """ Returns the first n Carmichael numbers.
2750
+
2751
+ Parameters
2752
+ ==========
2753
+
2754
+ n : Integer
2755
+
2756
+ See Also
2757
+ ========
2758
+
2759
+ is_carmichael
2760
+
2761
+ """
2762
+ i = 561
2763
+ carmichaels = []
2764
+
2765
+ while len(carmichaels) < n:
2766
+ if is_carmichael(i):
2767
+ carmichaels.append(i)
2768
+ i += 2
2769
+
2770
+ return carmichaels
2771
+
2772
+
2773
+ def dra(n, b):
2774
+ """
2775
+ Returns the additive digital root of a natural number ``n`` in base ``b``
2776
+ which is a single digit value obtained by an iterative process of summing
2777
+ digits, on each iteration using the result from the previous iteration to
2778
+ compute a digit sum.
2779
+
2780
+ Examples
2781
+ ========
2782
+
2783
+ >>> from sympy.ntheory.factor_ import dra
2784
+ >>> dra(3110, 12)
2785
+ 8
2786
+
2787
+ References
2788
+ ==========
2789
+
2790
+ .. [1] https://en.wikipedia.org/wiki/Digital_root
2791
+
2792
+ """
2793
+
2794
+ num = abs(as_int(n))
2795
+ b = as_int(b)
2796
+ if b <= 1:
2797
+ raise ValueError("Base should be an integer greater than 1")
2798
+
2799
+ if num == 0:
2800
+ return 0
2801
+
2802
+ return (1 + (num - 1) % (b - 1))
2803
+
2804
+
2805
+ def drm(n, b):
2806
+ """
2807
+ Returns the multiplicative digital root of a natural number ``n`` in a given
2808
+ base ``b`` which is a single digit value obtained by an iterative process of
2809
+ multiplying digits, on each iteration using the result from the previous
2810
+ iteration to compute the digit multiplication.
2811
+
2812
+ Examples
2813
+ ========
2814
+
2815
+ >>> from sympy.ntheory.factor_ import drm
2816
+ >>> drm(9876, 10)
2817
+ 0
2818
+
2819
+ >>> drm(49, 10)
2820
+ 8
2821
+
2822
+ References
2823
+ ==========
2824
+
2825
+ .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
2826
+
2827
+ """
2828
+
2829
+ n = abs(as_int(n))
2830
+ b = as_int(b)
2831
+ if b <= 1:
2832
+ raise ValueError("Base should be an integer greater than 1")
2833
+ while n > b:
2834
+ mul = 1
2835
+ while n > 1:
2836
+ n, r = divmod(n, b)
2837
+ if r == 0:
2838
+ return 0
2839
+ mul *= r
2840
+ n = mul
2841
+ return n
.venv/Lib/site-packages/sympy/ntheory/generate.py ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generating and counting primes.
3
+
4
+ """
5
+
6
+ from bisect import bisect, bisect_left
7
+ from itertools import count
8
+ # Using arrays for sieving instead of lists greatly reduces
9
+ # memory consumption
10
+ from array import array as _array
11
+
12
+ from sympy.core.random import randint
13
+ from sympy.external.gmpy import sqrt
14
+ from .primetest import isprime
15
+ from sympy.utilities.decorator import deprecated
16
+ from sympy.utilities.misc import as_int
17
+
18
+
19
+ def _as_int_ceiling(a):
20
+ """ Wrapping ceiling in as_int will raise an error if there was a problem
21
+ determining whether the expression was exactly an integer or not."""
22
+ from sympy.functions.elementary.integers import ceiling
23
+ return as_int(ceiling(a))
24
+
25
+
26
+ class Sieve:
27
+ """A list of prime numbers, implemented as a dynamically
28
+ growing sieve of Eratosthenes. When a lookup is requested involving
29
+ an odd number that has not been sieved, the sieve is automatically
30
+ extended up to that number. Implementation details limit the number of
31
+ primes to ``2^32-1``.
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy import sieve
37
+ >>> sieve._reset() # this line for doctest only
38
+ >>> 25 in sieve
39
+ False
40
+ >>> sieve._list
41
+ array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
42
+ """
43
+
44
+ # data shared (and updated) by all Sieve instances
45
+ def __init__(self, sieve_interval=1_000_000):
46
+ """ Initial parameters for the Sieve class.
47
+
48
+ Parameters
49
+ ==========
50
+
51
+ sieve_interval (int): Amount of memory to be used
52
+
53
+ Raises
54
+ ======
55
+
56
+ ValueError
57
+ If ``sieve_interval`` is not positive.
58
+
59
+ """
60
+ self._n = 6
61
+ self._list = _array('L', [2, 3, 5, 7, 11, 13]) # primes
62
+ self._tlist = _array('L', [0, 1, 1, 2, 2, 4]) # totient
63
+ self._mlist = _array('i', [0, 1, -1, -1, 0, -1]) # mobius
64
+ if sieve_interval <= 0:
65
+ raise ValueError("sieve_interval should be a positive integer")
66
+ self.sieve_interval = sieve_interval
67
+ assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
68
+
69
+ def __repr__(self):
70
+ return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
71
+ "%s sieve (%i): %i, %i, %i, ... %i, %i\n"
72
+ "%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
73
+ 'prime', len(self._list),
74
+ self._list[0], self._list[1], self._list[2],
75
+ self._list[-2], self._list[-1],
76
+ 'totient', len(self._tlist),
77
+ self._tlist[0], self._tlist[1],
78
+ self._tlist[2], self._tlist[-2], self._tlist[-1],
79
+ 'mobius', len(self._mlist),
80
+ self._mlist[0], self._mlist[1],
81
+ self._mlist[2], self._mlist[-2], self._mlist[-1])
82
+
83
+ def _reset(self, prime=None, totient=None, mobius=None):
84
+ """Reset all caches (default). To reset one or more set the
85
+ desired keyword to True."""
86
+ if all(i is None for i in (prime, totient, mobius)):
87
+ prime = totient = mobius = True
88
+ if prime:
89
+ self._list = self._list[:self._n]
90
+ if totient:
91
+ self._tlist = self._tlist[:self._n]
92
+ if mobius:
93
+ self._mlist = self._mlist[:self._n]
94
+
95
+ def extend(self, n):
96
+ """Grow the sieve to cover all primes <= n.
97
+
98
+ Examples
99
+ ========
100
+
101
+ >>> from sympy import sieve
102
+ >>> sieve._reset() # this line for doctest only
103
+ >>> sieve.extend(30)
104
+ >>> sieve[10] == 29
105
+ True
106
+ """
107
+ n = int(n)
108
+ # `num` is even at any point in the function.
109
+ # This satisfies the condition required by `self._primerange`.
110
+ num = self._list[-1] + 1
111
+ if n < num:
112
+ return
113
+ num2 = num**2
114
+ while num2 <= n:
115
+ self._list += _array('L', self._primerange(num, num2))
116
+ num, num2 = num2, num2**2
117
+ # Merge the sieves
118
+ self._list += _array('L', self._primerange(num, n + 1))
119
+
120
+ def _primerange(self, a, b):
121
+ """ Generate all prime numbers in the range (a, b).
122
+
123
+ Parameters
124
+ ==========
125
+
126
+ a, b : positive integers assuming the following conditions
127
+ * a is an even number
128
+ * 2 < self._list[-1] < a < b < nextprime(self._list[-1])**2
129
+
130
+ Yields
131
+ ======
132
+
133
+ p (int): prime numbers such that ``a < p < b``
134
+
135
+ Examples
136
+ ========
137
+
138
+ >>> from sympy.ntheory.generate import Sieve
139
+ >>> s = Sieve()
140
+ >>> s._list[-1]
141
+ 13
142
+ >>> list(s._primerange(18, 31))
143
+ [19, 23, 29]
144
+
145
+ """
146
+ if b % 2:
147
+ b -= 1
148
+ while a < b:
149
+ block_size = min(self.sieve_interval, (b - a) // 2)
150
+ # Create the list such that block[x] iff (a + 2x + 1) is prime.
151
+ # Note that even numbers are not considered here.
152
+ block = [True] * block_size
153
+ for p in self._list[1:bisect(self._list, sqrt(a + 2 * block_size + 1))]:
154
+ for t in range((-(a + 1 + p) // 2) % p, block_size, p):
155
+ block[t] = False
156
+ for idx, p in enumerate(block):
157
+ if p:
158
+ yield a + 2 * idx + 1
159
+ a += 2 * block_size
160
+
161
+ def extend_to_no(self, i):
162
+ """Extend to include the ith prime number.
163
+
164
+ Parameters
165
+ ==========
166
+
167
+ i : integer
168
+
169
+ Examples
170
+ ========
171
+
172
+ >>> from sympy import sieve
173
+ >>> sieve._reset() # this line for doctest only
174
+ >>> sieve.extend_to_no(9)
175
+ >>> sieve._list
176
+ array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
177
+
178
+ Notes
179
+ =====
180
+
181
+ The list is extended by 50% if it is too short, so it is
182
+ likely that it will be longer than requested.
183
+ """
184
+ i = as_int(i)
185
+ while len(self._list) < i:
186
+ self.extend(int(self._list[-1] * 1.5))
187
+
188
+ def primerange(self, a, b=None):
189
+ """Generate all prime numbers in the range [2, a) or [a, b).
190
+
191
+ Examples
192
+ ========
193
+
194
+ >>> from sympy import sieve, prime
195
+
196
+ All primes less than 19:
197
+
198
+ >>> print([i for i in sieve.primerange(19)])
199
+ [2, 3, 5, 7, 11, 13, 17]
200
+
201
+ All primes greater than or equal to 7 and less than 19:
202
+
203
+ >>> print([i for i in sieve.primerange(7, 19)])
204
+ [7, 11, 13, 17]
205
+
206
+ All primes through the 10th prime
207
+
208
+ >>> list(sieve.primerange(prime(10) + 1))
209
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
210
+
211
+ """
212
+ if b is None:
213
+ b = _as_int_ceiling(a)
214
+ a = 2
215
+ else:
216
+ a = max(2, _as_int_ceiling(a))
217
+ b = _as_int_ceiling(b)
218
+ if a >= b:
219
+ return
220
+ self.extend(b)
221
+ yield from self._list[bisect_left(self._list, a):
222
+ bisect_left(self._list, b)]
223
+
224
+ def totientrange(self, a, b):
225
+ """Generate all totient numbers for the range [a, b).
226
+
227
+ Examples
228
+ ========
229
+
230
+ >>> from sympy import sieve
231
+ >>> print([i for i in sieve.totientrange(7, 18)])
232
+ [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
233
+ """
234
+ a = max(1, _as_int_ceiling(a))
235
+ b = _as_int_ceiling(b)
236
+ n = len(self._tlist)
237
+ if a >= b:
238
+ return
239
+ elif b <= n:
240
+ for i in range(a, b):
241
+ yield self._tlist[i]
242
+ else:
243
+ self._tlist += _array('L', range(n, b))
244
+ for i in range(1, n):
245
+ ti = self._tlist[i]
246
+ if ti == i - 1:
247
+ startindex = (n + i - 1) // i * i
248
+ for j in range(startindex, b, i):
249
+ self._tlist[j] -= self._tlist[j] // i
250
+ if i >= a:
251
+ yield ti
252
+
253
+ for i in range(n, b):
254
+ ti = self._tlist[i]
255
+ if ti == i:
256
+ for j in range(i, b, i):
257
+ self._tlist[j] -= self._tlist[j] // i
258
+ if i >= a:
259
+ yield self._tlist[i]
260
+
261
+ def mobiusrange(self, a, b):
262
+ """Generate all mobius numbers for the range [a, b).
263
+
264
+ Parameters
265
+ ==========
266
+
267
+ a : integer
268
+ First number in range
269
+
270
+ b : integer
271
+ First number outside of range
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import sieve
277
+ >>> print([i for i in sieve.mobiusrange(7, 18)])
278
+ [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
279
+ """
280
+ a = max(1, _as_int_ceiling(a))
281
+ b = _as_int_ceiling(b)
282
+ n = len(self._mlist)
283
+ if a >= b:
284
+ return
285
+ elif b <= n:
286
+ for i in range(a, b):
287
+ yield self._mlist[i]
288
+ else:
289
+ self._mlist += _array('i', [0]*(b - n))
290
+ for i in range(1, n):
291
+ mi = self._mlist[i]
292
+ startindex = (n + i - 1) // i * i
293
+ for j in range(startindex, b, i):
294
+ self._mlist[j] -= mi
295
+ if i >= a:
296
+ yield mi
297
+
298
+ for i in range(n, b):
299
+ mi = self._mlist[i]
300
+ for j in range(2 * i, b, i):
301
+ self._mlist[j] -= mi
302
+ if i >= a:
303
+ yield mi
304
+
305
+ def search(self, n):
306
+ """Return the indices i, j of the primes that bound n.
307
+
308
+ If n is prime then i == j.
309
+
310
+ Although n can be an expression, if ceiling cannot convert
311
+ it to an integer then an n error will be raised.
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import sieve
317
+ >>> sieve.search(25)
318
+ (9, 10)
319
+ >>> sieve.search(23)
320
+ (9, 9)
321
+ """
322
+ test = _as_int_ceiling(n)
323
+ n = as_int(n)
324
+ if n < 2:
325
+ raise ValueError("n should be >= 2 but got: %s" % n)
326
+ if n > self._list[-1]:
327
+ self.extend(n)
328
+ b = bisect(self._list, n)
329
+ if self._list[b - 1] == test:
330
+ return b, b
331
+ else:
332
+ return b, b + 1
333
+
334
+ def __contains__(self, n):
335
+ try:
336
+ n = as_int(n)
337
+ assert n >= 2
338
+ except (ValueError, AssertionError):
339
+ return False
340
+ if n % 2 == 0:
341
+ return n == 2
342
+ a, b = self.search(n)
343
+ return a == b
344
+
345
+ def __iter__(self):
346
+ for n in count(1):
347
+ yield self[n]
348
+
349
+ def __getitem__(self, n):
350
+ """Return the nth prime number"""
351
+ if isinstance(n, slice):
352
+ self.extend_to_no(n.stop)
353
+ start = n.start if n.start is not None else 0
354
+ if start < 1:
355
+ # sieve[:5] would be empty (starting at -1), let's
356
+ # just be explicit and raise.
357
+ raise IndexError("Sieve indices start at 1.")
358
+ return self._list[start - 1:n.stop - 1:n.step]
359
+ else:
360
+ if n < 1:
361
+ # offset is one, so forbid explicit access to sieve[0]
362
+ # (would surprisingly return the last one).
363
+ raise IndexError("Sieve indices start at 1.")
364
+ n = as_int(n)
365
+ self.extend_to_no(n)
366
+ return self._list[n - 1]
367
+
368
+ # Generate a global object for repeated use in trial division etc
369
+ sieve = Sieve()
370
+
371
+ def prime(nth):
372
+ r"""
373
+ Return the nth prime number, where primes are indexed starting from 1:
374
+ prime(1) = 2, prime(2) = 3, etc.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ nth : int
380
+ The position of the prime number to return (must be a positive integer).
381
+
382
+ Returns
383
+ =======
384
+
385
+ int
386
+ The nth prime number.
387
+
388
+ Examples
389
+ ========
390
+
391
+ >>> from sympy import prime
392
+ >>> prime(10)
393
+ 29
394
+ >>> prime(1)
395
+ 2
396
+ >>> prime(100000)
397
+ 1299709
398
+
399
+ See Also
400
+ ========
401
+
402
+ sympy.ntheory.primetest.isprime : Test if a number is prime.
403
+ primerange : Generate all primes in a given range.
404
+ primepi : Return the number of primes less than or equal to a given number.
405
+
406
+ References
407
+ ==========
408
+
409
+ .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem
410
+ .. [2] https://en.wikipedia.org/wiki/Logarithmic_integral_function
411
+ .. [3] https://en.wikipedia.org/wiki/Skewes%27_number
412
+ """
413
+ n = as_int(nth)
414
+ if n < 1:
415
+ raise ValueError("nth must be a positive integer; prime(1) == 2")
416
+
417
+ # Check if n is within the sieve range
418
+ if n <= len(sieve._list):
419
+ return sieve[n]
420
+
421
+ from sympy.functions.elementary.exponential import log
422
+ from sympy.functions.special.error_functions import li
423
+
424
+ if n < 1000:
425
+ # Extend sieve up to 8*n as this is empirically sufficient
426
+ sieve.extend(8 * n)
427
+ return sieve[n]
428
+
429
+ a = 2
430
+ # Estimate an upper bound for the nth prime using the prime number theorem
431
+ b = int(n * (log(n).evalf() + log(log(n)).evalf()))
432
+
433
+ # Binary search for the least m such that li(m) > n
434
+ while a < b:
435
+ mid = (a + b) >> 1
436
+ if li(mid).evalf() > n:
437
+ b = mid
438
+ else:
439
+ a = mid + 1
440
+
441
+ return nextprime(a - 1, n - _primepi(a - 1))
442
+
443
+
444
+ @deprecated("""\
445
+ The `sympy.ntheory.generate.primepi` has been moved to `sympy.functions.combinatorial.numbers.primepi`.""",
446
+ deprecated_since_version="1.13",
447
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
448
+ def primepi(n):
449
+ r""" Represents the prime counting function pi(n) = the number
450
+ of prime numbers less than or equal to n.
451
+
452
+ .. deprecated:: 1.13
453
+
454
+ The ``primepi`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primepi`
455
+ instead. See its documentation for more information. See
456
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
457
+
458
+ Algorithm Description:
459
+
460
+ In sieve method, we remove all multiples of prime p
461
+ except p itself.
462
+
463
+ Let phi(i,j) be the number of integers 2 <= k <= i
464
+ which remain after sieving from primes less than
465
+ or equal to j.
466
+ Clearly, pi(n) = phi(n, sqrt(n))
467
+
468
+ If j is not a prime,
469
+ phi(i,j) = phi(i, j - 1)
470
+
471
+ if j is a prime,
472
+ We remove all numbers(except j) whose
473
+ smallest prime factor is j.
474
+
475
+ Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
476
+ Now, after sieving from primes $\le j - 1$,
477
+ a must remain
478
+ (because x, and hence a has no prime factor $\le j - 1$)
479
+ Clearly, there are phi(i / j, j - 1) such a
480
+ which remain on sieving from primes $\le j - 1$
481
+
482
+ Now, if a is a prime less than equal to j - 1,
483
+ $x= j \times a$ has smallest prime factor = a, and
484
+ has already been removed(by sieving from a).
485
+ So, we do not need to remove it again.
486
+ (Note: there will be pi(j - 1) such x)
487
+
488
+ Thus, number of x, that will be removed are:
489
+ phi(i / j, j - 1) - phi(j - 1, j - 1)
490
+ (Note that pi(j - 1) = phi(j - 1, j - 1))
491
+
492
+ $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
493
+
494
+ So,following recursion is used and implemented as dp:
495
+
496
+ phi(a, b) = phi(a, b - 1), if b is not a prime
497
+ phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
498
+
499
+ Clearly a is always of the form floor(n / k),
500
+ which can take at most $2\sqrt{n}$ values.
501
+ Two arrays arr1,arr2 are maintained
502
+ arr1[i] = phi(i, j),
503
+ arr2[i] = phi(n // i, j)
504
+
505
+ Finally the answer is arr2[1]
506
+
507
+ Examples
508
+ ========
509
+
510
+ >>> from sympy import primepi, prime, prevprime, isprime
511
+ >>> primepi(25)
512
+ 9
513
+
514
+ So there are 9 primes less than or equal to 25. Is 25 prime?
515
+
516
+ >>> isprime(25)
517
+ False
518
+
519
+ It is not. So the first prime less than 25 must be the
520
+ 9th prime:
521
+
522
+ >>> prevprime(25) == prime(9)
523
+ True
524
+
525
+ See Also
526
+ ========
527
+
528
+ sympy.ntheory.primetest.isprime : Test if n is prime
529
+ primerange : Generate all primes in a given range
530
+ prime : Return the nth prime
531
+ """
532
+ from sympy.functions.combinatorial.numbers import primepi as func_primepi
533
+ return func_primepi(n)
534
+
535
+
536
+ def _primepi(n:int) -> int:
537
+ r""" Represents the prime counting function pi(n) = the number
538
+ of prime numbers less than or equal to n.
539
+
540
+ Explanation
541
+ ===========
542
+
543
+ In sieve method, we remove all multiples of prime p
544
+ except p itself.
545
+
546
+ Let phi(i,j) be the number of integers 2 <= k <= i
547
+ which remain after sieving from primes less than
548
+ or equal to j.
549
+ Clearly, pi(n) = phi(n, sqrt(n))
550
+
551
+ If j is not a prime,
552
+ phi(i,j) = phi(i, j - 1)
553
+
554
+ if j is a prime,
555
+ We remove all numbers(except j) whose
556
+ smallest prime factor is j.
557
+
558
+ Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
559
+ Now, after sieving from primes $\le j - 1$,
560
+ a must remain
561
+ (because x, and hence a has no prime factor $\le j - 1$)
562
+ Clearly, there are phi(i / j, j - 1) such a
563
+ which remain on sieving from primes $\le j - 1$
564
+
565
+ Now, if a is a prime less than equal to j - 1,
566
+ $x= j \times a$ has smallest prime factor = a, and
567
+ has already been removed(by sieving from a).
568
+ So, we do not need to remove it again.
569
+ (Note: there will be pi(j - 1) such x)
570
+
571
+ Thus, number of x, that will be removed are:
572
+ phi(i / j, j - 1) - phi(j - 1, j - 1)
573
+ (Note that pi(j - 1) = phi(j - 1, j - 1))
574
+
575
+ $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
576
+
577
+ So,following recursion is used and implemented as dp:
578
+
579
+ phi(a, b) = phi(a, b - 1), if b is not a prime
580
+ phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
581
+
582
+ Clearly a is always of the form floor(n / k),
583
+ which can take at most $2\sqrt{n}$ values.
584
+ Two arrays arr1,arr2 are maintained
585
+ arr1[i] = phi(i, j),
586
+ arr2[i] = phi(n // i, j)
587
+
588
+ Finally the answer is arr2[1]
589
+
590
+ Parameters
591
+ ==========
592
+
593
+ n : int
594
+
595
+ """
596
+ if n < 2:
597
+ return 0
598
+ if n <= sieve._list[-1]:
599
+ return sieve.search(n)[0]
600
+ lim = sqrt(n)
601
+ arr1 = [(i + 1) >> 1 for i in range(lim + 1)]
602
+ arr2 = [0] + [(n//i + 1) >> 1 for i in range(1, lim + 1)]
603
+ skip = [False] * (lim + 1)
604
+ for i in range(3, lim + 1, 2):
605
+ # Presently, arr1[k]=phi(k,i - 1),
606
+ # arr2[k] = phi(n // k,i - 1) # not all k's do this
607
+ if skip[i]:
608
+ # skip if i is a composite number
609
+ continue
610
+ p = arr1[i - 1]
611
+ for j in range(i, lim + 1, i):
612
+ skip[j] = True
613
+ # update arr2
614
+ # phi(n/j, i) = phi(n/j, i-1) - phi(n/(i*j), i-1) + phi(i-1, i-1)
615
+ for j in range(1, min(n // (i * i), lim) + 1, 2):
616
+ # No need for arr2[j] in j such that skip[j] is True to
617
+ # compute the final required arr2[1].
618
+ if skip[j]:
619
+ continue
620
+ st = i * j
621
+ if st <= lim:
622
+ arr2[j] -= arr2[st] - p
623
+ else:
624
+ arr2[j] -= arr1[n // st] - p
625
+ # update arr1
626
+ # phi(j, i) = phi(j, i-1) - phi(j/i, i-1) + phi(i-1, i-1)
627
+ # where the range below i**2 is fixed and
628
+ # does not need to be calculated.
629
+ for j in range(lim, min(lim, i*i - 1), -1):
630
+ arr1[j] -= arr1[j // i] - p
631
+ return arr2[1]
632
+
633
+
634
+ def nextprime(n, ith=1):
635
+ """ Return the ith prime greater than n.
636
+
637
+ Parameters
638
+ ==========
639
+
640
+ n : integer
641
+ ith : positive integer
642
+
643
+ Returns
644
+ =======
645
+
646
+ int : Return the ith prime greater than n
647
+
648
+ Raises
649
+ ======
650
+
651
+ ValueError
652
+ If ``ith <= 0``.
653
+ If ``n`` or ``ith`` is not an integer.
654
+
655
+ Notes
656
+ =====
657
+
658
+ Potential primes are located at 6*j +/- 1. This
659
+ property is used during searching.
660
+
661
+ >>> from sympy import nextprime
662
+ >>> [(i, nextprime(i)) for i in range(10, 15)]
663
+ [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
664
+ >>> nextprime(2, ith=2) # the 2nd prime after 2
665
+ 5
666
+
667
+ See Also
668
+ ========
669
+
670
+ prevprime : Return the largest prime smaller than n
671
+ primerange : Generate all primes in a given range
672
+
673
+ """
674
+ n = int(n)
675
+ i = as_int(ith)
676
+ if i <= 0:
677
+ raise ValueError("ith should be positive")
678
+ if n < 2:
679
+ n = 2
680
+ i -= 1
681
+ if n <= sieve._list[-2]:
682
+ l, _ = sieve.search(n)
683
+ if l + i - 1 < len(sieve._list):
684
+ return sieve._list[l + i - 1]
685
+ n = sieve._list[-1]
686
+ i += l - len(sieve._list)
687
+ nn = 6*(n//6)
688
+ if nn == n:
689
+ n += 1
690
+ if isprime(n):
691
+ i -= 1
692
+ if not i:
693
+ return n
694
+ n += 4
695
+ elif n - nn == 5:
696
+ n += 2
697
+ if isprime(n):
698
+ i -= 1
699
+ if not i:
700
+ return n
701
+ n += 4
702
+ else:
703
+ n = nn + 5
704
+ while 1:
705
+ if isprime(n):
706
+ i -= 1
707
+ if not i:
708
+ return n
709
+ n += 2
710
+ if isprime(n):
711
+ i -= 1
712
+ if not i:
713
+ return n
714
+ n += 4
715
+
716
+
717
+ def prevprime(n):
718
+ """ Return the largest prime smaller than n.
719
+
720
+ Notes
721
+ =====
722
+
723
+ Potential primes are located at 6*j +/- 1. This
724
+ property is used during searching.
725
+
726
+ >>> from sympy import prevprime
727
+ >>> [(i, prevprime(i)) for i in range(10, 15)]
728
+ [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
729
+
730
+ See Also
731
+ ========
732
+
733
+ nextprime : Return the ith prime greater than n
734
+ primerange : Generates all primes in a given range
735
+ """
736
+ n = _as_int_ceiling(n)
737
+ if n < 3:
738
+ raise ValueError("no preceding primes")
739
+ if n < 8:
740
+ return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
741
+ if n <= sieve._list[-1]:
742
+ l, u = sieve.search(n)
743
+ if l == u:
744
+ return sieve[l-1]
745
+ else:
746
+ return sieve[l]
747
+ nn = 6*(n//6)
748
+ if n - nn <= 1:
749
+ n = nn - 1
750
+ if isprime(n):
751
+ return n
752
+ n -= 4
753
+ else:
754
+ n = nn + 1
755
+ while 1:
756
+ if isprime(n):
757
+ return n
758
+ n -= 2
759
+ if isprime(n):
760
+ return n
761
+ n -= 4
762
+
763
+
764
+ def primerange(a, b=None):
765
+ """ Generate a list of all prime numbers in the range [2, a),
766
+ or [a, b).
767
+
768
+ If the range exists in the default sieve, the values will
769
+ be returned from there; otherwise values will be returned
770
+ but will not modify the sieve.
771
+
772
+ Examples
773
+ ========
774
+
775
+ >>> from sympy import primerange, prime
776
+
777
+ All primes less than 19:
778
+
779
+ >>> list(primerange(19))
780
+ [2, 3, 5, 7, 11, 13, 17]
781
+
782
+ All primes greater than or equal to 7 and less than 19:
783
+
784
+ >>> list(primerange(7, 19))
785
+ [7, 11, 13, 17]
786
+
787
+ All primes through the 10th prime
788
+
789
+ >>> list(primerange(prime(10) + 1))
790
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
791
+
792
+ The Sieve method, primerange, is generally faster but it will
793
+ occupy more memory as the sieve stores values. The default
794
+ instance of Sieve, named sieve, can be used:
795
+
796
+ >>> from sympy import sieve
797
+ >>> list(sieve.primerange(1, 30))
798
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
799
+
800
+ Notes
801
+ =====
802
+
803
+ Some famous conjectures about the occurrence of primes in a given
804
+ range are [1]:
805
+
806
+ - Twin primes: though often not, the following will give 2 primes
807
+ an infinite number of times:
808
+ primerange(6*n - 1, 6*n + 2)
809
+ - Legendre's: the following always yields at least one prime
810
+ primerange(n**2, (n+1)**2+1)
811
+ - Bertrand's (proven): there is always a prime in the range
812
+ primerange(n, 2*n)
813
+ - Brocard's: there are at least four primes in the range
814
+ primerange(prime(n)**2, prime(n+1)**2)
815
+
816
+ The average gap between primes is log(n) [2]; the gap between
817
+ primes can be arbitrarily large since sequences of composite
818
+ numbers are arbitrarily large, e.g. the numbers in the sequence
819
+ n! + 2, n! + 3 ... n! + n are all composite.
820
+
821
+ See Also
822
+ ========
823
+
824
+ prime : Return the nth prime
825
+ nextprime : Return the ith prime greater than n
826
+ prevprime : Return the largest prime smaller than n
827
+ randprime : Returns a random prime in a given range
828
+ primorial : Returns the product of primes based on condition
829
+ Sieve.primerange : return range from already computed primes
830
+ or extend the sieve to contain the requested
831
+ range.
832
+
833
+ References
834
+ ==========
835
+
836
+ .. [1] https://en.wikipedia.org/wiki/Prime_number
837
+ .. [2] https://primes.utm.edu/notes/gaps.html
838
+ """
839
+ if b is None:
840
+ a, b = 2, a
841
+ if a >= b:
842
+ return
843
+ # If we already have the range, return it.
844
+ largest_known_prime = sieve._list[-1]
845
+ if b <= largest_known_prime:
846
+ yield from sieve.primerange(a, b)
847
+ return
848
+ # If we know some of it, return it.
849
+ if a <= largest_known_prime:
850
+ yield from sieve._list[bisect_left(sieve._list, a):]
851
+ a = largest_known_prime + 1
852
+ elif a % 2:
853
+ a -= 1
854
+ tail = min(b, (largest_known_prime)**2)
855
+ if a < tail:
856
+ yield from sieve._primerange(a, tail)
857
+ a = tail
858
+ if b <= a:
859
+ return
860
+ # otherwise compute, without storing, the desired range.
861
+ while 1:
862
+ a = nextprime(a)
863
+ if a < b:
864
+ yield a
865
+ else:
866
+ return
867
+
868
+
869
+ def randprime(a, b):
870
+ """ Return a random prime number in the range [a, b).
871
+
872
+ Bertrand's postulate assures that
873
+ randprime(a, 2*a) will always succeed for a > 1.
874
+
875
+ Note that due to implementation difficulties,
876
+ the prime numbers chosen are not uniformly random.
877
+ For example, there are two primes in the range [112, 128),
878
+ ``113`` and ``127``, but ``randprime(112, 128)`` returns ``127``
879
+ with a probability of 15/17.
880
+
881
+ Examples
882
+ ========
883
+
884
+ >>> from sympy import randprime, isprime
885
+ >>> randprime(1, 30) #doctest: +SKIP
886
+ 13
887
+ >>> isprime(randprime(1, 30))
888
+ True
889
+
890
+ See Also
891
+ ========
892
+
893
+ primerange : Generate all primes in a given range
894
+
895
+ References
896
+ ==========
897
+
898
+ .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
899
+
900
+ """
901
+ if a >= b:
902
+ return
903
+ a, b = map(int, (a, b))
904
+ n = randint(a - 1, b)
905
+ p = nextprime(n)
906
+ if p >= b:
907
+ p = prevprime(b)
908
+ if p < a:
909
+ raise ValueError("no primes exist in the specified range")
910
+ return p
911
+
912
+
913
+ def primorial(n, nth=True):
914
+ """
915
+ Returns the product of the first n primes (default) or
916
+ the primes less than or equal to n (when ``nth=False``).
917
+
918
+ Examples
919
+ ========
920
+
921
+ >>> from sympy.ntheory.generate import primorial, primerange
922
+ >>> from sympy import factorint, Mul, primefactors, sqrt
923
+ >>> primorial(4) # the first 4 primes are 2, 3, 5, 7
924
+ 210
925
+ >>> primorial(4, nth=False) # primes <= 4 are 2 and 3
926
+ 6
927
+ >>> primorial(1)
928
+ 2
929
+ >>> primorial(1, nth=False)
930
+ 1
931
+ >>> primorial(sqrt(101), nth=False)
932
+ 210
933
+
934
+ One can argue that the primes are infinite since if you take
935
+ a set of primes and multiply them together (e.g. the primorial) and
936
+ then add or subtract 1, the result cannot be divided by any of the
937
+ original factors, hence either 1 or more new primes must divide this
938
+ product of primes.
939
+
940
+ In this case, the number itself is a new prime:
941
+
942
+ >>> factorint(primorial(4) + 1)
943
+ {211: 1}
944
+
945
+ In this case two new primes are the factors:
946
+
947
+ >>> factorint(primorial(4) - 1)
948
+ {11: 1, 19: 1}
949
+
950
+ Here, some primes smaller and larger than the primes multiplied together
951
+ are obtained:
952
+
953
+ >>> p = list(primerange(10, 20))
954
+ >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
955
+ [2, 5, 31, 149]
956
+
957
+ See Also
958
+ ========
959
+
960
+ primerange : Generate all primes in a given range
961
+
962
+ """
963
+ if nth:
964
+ n = as_int(n)
965
+ else:
966
+ n = int(n)
967
+ if n < 1:
968
+ raise ValueError("primorial argument must be >= 1")
969
+ p = 1
970
+ if nth:
971
+ for i in range(1, n + 1):
972
+ p *= prime(i)
973
+ else:
974
+ for i in primerange(2, n + 1):
975
+ p *= i
976
+ return p
977
+
978
+
979
+ def cycle_length(f, x0, nmax=None, values=False):
980
+ """For a given iterated sequence, return a generator that gives
981
+ the length of the iterated cycle (lambda) and the length of terms
982
+ before the cycle begins (mu); if ``values`` is True then the
983
+ terms of the sequence will be returned instead. The sequence is
984
+ started with value ``x0``.
985
+
986
+ Note: more than the first lambda + mu terms may be returned and this
987
+ is the cost of cycle detection with Brent's method; there are, however,
988
+ generally less terms calculated than would have been calculated if the
989
+ proper ending point were determined, e.g. by using Floyd's method.
990
+
991
+ >>> from sympy.ntheory.generate import cycle_length
992
+
993
+ This will yield successive values of i <-- func(i):
994
+
995
+ >>> def gen(func, i):
996
+ ... while 1:
997
+ ... yield i
998
+ ... i = func(i)
999
+ ...
1000
+
1001
+ A function is defined:
1002
+
1003
+ >>> func = lambda i: (i**2 + 1) % 51
1004
+
1005
+ and given a seed of 4 and the mu and lambda terms calculated:
1006
+
1007
+ >>> next(cycle_length(func, 4))
1008
+ (6, 3)
1009
+
1010
+ We can see what is meant by looking at the output:
1011
+
1012
+ >>> iter = cycle_length(func, 4, values=True)
1013
+ >>> list(iter)
1014
+ [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
1015
+
1016
+ There are 6 repeating values after the first 3.
1017
+
1018
+ If a sequence is suspected of being longer than you might wish, ``nmax``
1019
+ can be used to exit early (and mu will be returned as None):
1020
+
1021
+ >>> next(cycle_length(func, 4, nmax = 4))
1022
+ (4, None)
1023
+ >>> list(cycle_length(func, 4, nmax = 4, values=True))
1024
+ [4, 17, 35, 2]
1025
+
1026
+ Code modified from:
1027
+ https://en.wikipedia.org/wiki/Cycle_detection.
1028
+ """
1029
+
1030
+ nmax = int(nmax or 0)
1031
+
1032
+ # main phase: search successive powers of two
1033
+ power = lam = 1
1034
+ tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
1035
+ i = 1
1036
+ if values:
1037
+ yield tortoise
1038
+ while tortoise != hare and (not nmax or i < nmax):
1039
+ i += 1
1040
+ if power == lam: # time to start a new power of two?
1041
+ tortoise = hare
1042
+ power *= 2
1043
+ lam = 0
1044
+ if values:
1045
+ yield hare
1046
+ hare = f(hare)
1047
+ lam += 1
1048
+ if nmax and i == nmax:
1049
+ if values:
1050
+ return
1051
+ else:
1052
+ yield nmax, None
1053
+ return
1054
+ if not values:
1055
+ # Find the position of the first repetition of length lambda
1056
+ mu = 0
1057
+ tortoise = hare = x0
1058
+ for i in range(lam):
1059
+ hare = f(hare)
1060
+ while tortoise != hare:
1061
+ tortoise = f(tortoise)
1062
+ hare = f(hare)
1063
+ mu += 1
1064
+ yield lam, mu
1065
+
1066
+
1067
+ def composite(nth):
1068
+ """ Return the nth composite number, with the composite numbers indexed as
1069
+ composite(1) = 4, composite(2) = 6, etc....
1070
+
1071
+ Examples
1072
+ ========
1073
+
1074
+ >>> from sympy import composite
1075
+ >>> composite(36)
1076
+ 52
1077
+ >>> composite(1)
1078
+ 4
1079
+ >>> composite(17737)
1080
+ 20000
1081
+
1082
+ See Also
1083
+ ========
1084
+
1085
+ sympy.ntheory.primetest.isprime : Test if n is prime
1086
+ primerange : Generate all primes in a given range
1087
+ primepi : Return the number of primes less than or equal to n
1088
+ prime : Return the nth prime
1089
+ compositepi : Return the number of positive composite numbers less than or equal to n
1090
+ """
1091
+ n = as_int(nth)
1092
+ if n < 1:
1093
+ raise ValueError("nth must be a positive integer; composite(1) == 4")
1094
+ composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
1095
+ if n <= 10:
1096
+ return composite_arr[n - 1]
1097
+
1098
+ a, b = 4, sieve._list[-1]
1099
+ if n <= b - _primepi(b) - 1:
1100
+ while a < b - 1:
1101
+ mid = (a + b) >> 1
1102
+ if mid - _primepi(mid) - 1 > n:
1103
+ b = mid
1104
+ else:
1105
+ a = mid
1106
+ if isprime(a):
1107
+ a -= 1
1108
+ return a
1109
+
1110
+ from sympy.functions.elementary.exponential import log
1111
+ from sympy.functions.special.error_functions import li
1112
+ a = 4 # Lower bound for binary search
1113
+ b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
1114
+
1115
+ while a < b:
1116
+ mid = (a + b) >> 1
1117
+ if mid - li(mid) - 1 > n:
1118
+ b = mid
1119
+ else:
1120
+ a = mid + 1
1121
+
1122
+ n_composites = a - _primepi(a) - 1
1123
+ while n_composites > n:
1124
+ if not isprime(a):
1125
+ n_composites -= 1
1126
+ a -= 1
1127
+ if isprime(a):
1128
+ a -= 1
1129
+ return a
1130
+
1131
+
1132
+ def compositepi(n):
1133
+ """ Return the number of positive composite numbers less than or equal to n.
1134
+ The first positive composite is 4, i.e. compositepi(4) = 1.
1135
+
1136
+ Examples
1137
+ ========
1138
+
1139
+ >>> from sympy import compositepi
1140
+ >>> compositepi(25)
1141
+ 15
1142
+ >>> compositepi(1000)
1143
+ 831
1144
+
1145
+ See Also
1146
+ ========
1147
+
1148
+ sympy.ntheory.primetest.isprime : Test if n is prime
1149
+ primerange : Generate all primes in a given range
1150
+ prime : Return the nth prime
1151
+ primepi : Return the number of primes less than or equal to n
1152
+ composite : Return the nth composite number
1153
+ """
1154
+ n = int(n)
1155
+ if n < 4:
1156
+ return 0
1157
+ return n - _primepi(n) - 1
.venv/Lib/site-packages/sympy/ntheory/modular.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.external.gmpy import gcd, gcdext
4
+ from sympy.ntheory.primetest import isprime
5
+ from sympy.polys.domains import ZZ
6
+ from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
7
+ from sympy.utilities.misc import as_int
8
+
9
+
10
+ def symmetric_residue(a, m):
11
+ """Return the residual mod m such that it is within half of the modulus.
12
+
13
+ >>> from sympy.ntheory.modular import symmetric_residue
14
+ >>> symmetric_residue(1, 6)
15
+ 1
16
+ >>> symmetric_residue(4, 6)
17
+ -2
18
+ """
19
+ if a <= m // 2:
20
+ return a
21
+ return a - m
22
+
23
+
24
+ def crt(m, v, symmetric=False, check=True):
25
+ r"""Chinese Remainder Theorem.
26
+
27
+ The moduli in m are assumed to be pairwise coprime. The output
28
+ is then an integer f, such that f = v_i mod m_i for each pair out
29
+ of v and m. If ``symmetric`` is False a positive integer will be
30
+ returned, else \|f\| will be less than or equal to the LCM of the
31
+ moduli, and thus f may be negative.
32
+
33
+ If the moduli are not co-prime the correct result will be returned
34
+ if/when the test of the result is found to be incorrect. This result
35
+ will be None if there is no solution.
36
+
37
+ The keyword ``check`` can be set to False if it is known that the moduli
38
+ are coprime.
39
+
40
+ Examples
41
+ ========
42
+
43
+ As an example consider a set of residues ``U = [49, 76, 65]``
44
+ and a set of moduli ``M = [99, 97, 95]``. Then we have::
45
+
46
+ >>> from sympy.ntheory.modular import crt
47
+
48
+ >>> crt([99, 97, 95], [49, 76, 65])
49
+ (639985, 912285)
50
+
51
+ This is the correct result because::
52
+
53
+ >>> [639985 % m for m in [99, 97, 95]]
54
+ [49, 76, 65]
55
+
56
+ If the moduli are not co-prime, you may receive an incorrect result
57
+ if you use ``check=False``:
58
+
59
+ >>> crt([12, 6, 17], [3, 4, 2], check=False)
60
+ (954, 1224)
61
+ >>> [954 % m for m in [12, 6, 17]]
62
+ [6, 0, 2]
63
+ >>> crt([12, 6, 17], [3, 4, 2]) is None
64
+ True
65
+ >>> crt([3, 6], [2, 5])
66
+ (5, 6)
67
+
68
+ Note: the order of gf_crt's arguments is reversed relative to crt,
69
+ and that solve_congruence takes residue, modulus pairs.
70
+
71
+ Programmer's note: rather than checking that all pairs of moduli share
72
+ no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
73
+ that there is no factor in common, a check that the result gives the
74
+ indicated residuals is performed -- an O(n) operation.
75
+
76
+ See Also
77
+ ========
78
+
79
+ solve_congruence
80
+ sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
81
+ """
82
+ if check:
83
+ m = list(map(as_int, m))
84
+ v = list(map(as_int, v))
85
+
86
+ result = gf_crt(v, m, ZZ)
87
+ mm = prod(m)
88
+
89
+ if check:
90
+ if not all(v % m == result % m for v, m in zip(v, m)):
91
+ result = solve_congruence(*list(zip(v, m)),
92
+ check=False, symmetric=symmetric)
93
+ if result is None:
94
+ return result
95
+ result, mm = result
96
+
97
+ if symmetric:
98
+ return int(symmetric_residue(result, mm)), int(mm)
99
+ return int(result), int(mm)
100
+
101
+
102
+ def crt1(m):
103
+ """First part of Chinese Remainder Theorem, for multiple application.
104
+
105
+ Examples
106
+ ========
107
+
108
+ >>> from sympy.ntheory.modular import crt, crt1, crt2
109
+ >>> m = [99, 97, 95]
110
+ >>> v = [49, 76, 65]
111
+
112
+ The following two codes have the same result.
113
+
114
+ >>> crt(m, v)
115
+ (639985, 912285)
116
+
117
+ >>> mm, e, s = crt1(m)
118
+ >>> crt2(m, v, mm, e, s)
119
+ (639985, 912285)
120
+
121
+ However, it is faster when we want to fix ``m`` and
122
+ compute for multiple ``v``, i.e. the following cases:
123
+
124
+ >>> mm, e, s = crt1(m)
125
+ >>> vs = [[52, 21, 37], [19, 46, 76]]
126
+ >>> for v in vs:
127
+ ... print(crt2(m, v, mm, e, s))
128
+ (397042, 912285)
129
+ (803206, 912285)
130
+
131
+ See Also
132
+ ========
133
+
134
+ sympy.polys.galoistools.gf_crt1 : low level crt routine used by this routine
135
+ sympy.ntheory.modular.crt
136
+ sympy.ntheory.modular.crt2
137
+
138
+ """
139
+
140
+ return gf_crt1(m, ZZ)
141
+
142
+
143
+ def crt2(m, v, mm, e, s, symmetric=False):
144
+ """Second part of Chinese Remainder Theorem, for multiple application.
145
+
146
+ See ``crt1`` for usage.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.ntheory.modular import crt1, crt2
152
+ >>> mm, e, s = crt1([18, 42, 6])
153
+ >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
154
+ (0, 4536)
155
+
156
+ See Also
157
+ ========
158
+
159
+ sympy.polys.galoistools.gf_crt2 : low level crt routine used by this routine
160
+ sympy.ntheory.modular.crt
161
+ sympy.ntheory.modular.crt1
162
+
163
+ """
164
+
165
+ result = gf_crt2(v, m, mm, e, s, ZZ)
166
+
167
+ if symmetric:
168
+ return int(symmetric_residue(result, mm)), int(mm)
169
+ return int(result), int(mm)
170
+
171
+
172
+ def solve_congruence(*remainder_modulus_pairs, **hint):
173
+ """Compute the integer ``n`` that has the residual ``ai`` when it is
174
+ divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
175
+ this function: ((a1, m1), (a2, m2), ...). If there is no solution,
176
+ return None. Otherwise return ``n`` and its modulus.
177
+
178
+ The ``mi`` values need not be co-prime. If it is known that the moduli are
179
+ not co-prime then the hint ``check`` can be set to False (default=True) and
180
+ the check for a quicker solution via crt() (valid when the moduli are
181
+ co-prime) will be skipped.
182
+
183
+ If the hint ``symmetric`` is True (default is False), the value of ``n``
184
+ will be within 1/2 of the modulus, possibly negative.
185
+
186
+ Examples
187
+ ========
188
+
189
+ >>> from sympy.ntheory.modular import solve_congruence
190
+
191
+ What number is 2 mod 3, 3 mod 5 and 2 mod 7?
192
+
193
+ >>> solve_congruence((2, 3), (3, 5), (2, 7))
194
+ (23, 105)
195
+ >>> [23 % m for m in [3, 5, 7]]
196
+ [2, 3, 2]
197
+
198
+ If you prefer to work with all remainder in one list and
199
+ all moduli in another, send the arguments like this:
200
+
201
+ >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
202
+ (23, 105)
203
+
204
+ The moduli need not be co-prime; in this case there may or
205
+ may not be a solution:
206
+
207
+ >>> solve_congruence((2, 3), (4, 6)) is None
208
+ True
209
+
210
+ >>> solve_congruence((2, 3), (5, 6))
211
+ (5, 6)
212
+
213
+ The symmetric flag will make the result be within 1/2 of the modulus:
214
+
215
+ >>> solve_congruence((2, 3), (5, 6), symmetric=True)
216
+ (-1, 6)
217
+
218
+ See Also
219
+ ========
220
+
221
+ crt : high level routine implementing the Chinese Remainder Theorem
222
+
223
+ """
224
+ def combine(c1, c2):
225
+ """Return the tuple (a, m) which satisfies the requirement
226
+ that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
227
+
228
+ References
229
+ ==========
230
+
231
+ .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution
232
+ """
233
+ a1, m1 = c1
234
+ a2, m2 = c2
235
+ a, b, c = m1, a2 - a1, m2
236
+ g = gcd(a, b, c)
237
+ a, b, c = [i//g for i in [a, b, c]]
238
+ if a != 1:
239
+ g, inv_a, _ = gcdext(a, c)
240
+ if g != 1:
241
+ return None
242
+ b *= inv_a
243
+ a, m = a1 + m1*b, m1*c
244
+ return a, m
245
+
246
+ rm = remainder_modulus_pairs
247
+ symmetric = hint.get('symmetric', False)
248
+
249
+ if hint.get('check', True):
250
+ rm = [(as_int(r), as_int(m)) for r, m in rm]
251
+
252
+ # ignore redundant pairs but raise an error otherwise; also
253
+ # make sure that a unique set of bases is sent to gf_crt if
254
+ # they are all prime.
255
+ #
256
+ # The routine will work out less-trivial violations and
257
+ # return None, e.g. for the pairs (1,3) and (14,42) there
258
+ # is no answer because 14 mod 42 (having a gcd of 14) implies
259
+ # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
260
+ # which, being 0 mod 3, is inconsistent with 1 mod 3. But to
261
+ # preprocess the input beyond checking of another pair with 42
262
+ # or 3 as the modulus (for this example) is not necessary.
263
+ uniq = {}
264
+ for r, m in rm:
265
+ r %= m
266
+ if m in uniq:
267
+ if r != uniq[m]:
268
+ return None
269
+ continue
270
+ uniq[m] = r
271
+ rm = [(r, m) for m, r in uniq.items()]
272
+ del uniq
273
+
274
+ # if the moduli are co-prime, the crt will be significantly faster;
275
+ # checking all pairs for being co-prime gets to be slow but a prime
276
+ # test is a good trade-off
277
+ if all(isprime(m) for r, m in rm):
278
+ r, m = list(zip(*rm))
279
+ return crt(m, r, symmetric=symmetric, check=False)
280
+
281
+ rv = (0, 1)
282
+ for rmi in rm:
283
+ rv = combine(rv, rmi)
284
+ if rv is None:
285
+ break
286
+ n, m = rv
287
+ n = n % m
288
+ else:
289
+ if symmetric:
290
+ return symmetric_residue(n, m), m
291
+ return n, m
.venv/Lib/site-packages/sympy/ntheory/multinomial.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities.misc import as_int
2
+
3
+
4
+ def binomial_coefficients(n):
5
+ """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
6
+ :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
7
+
8
+ Examples
9
+ ========
10
+
11
+ >>> from sympy.ntheory import binomial_coefficients
12
+ >>> binomial_coefficients(9)
13
+ {(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
14
+ (4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
15
+
16
+ See Also
17
+ ========
18
+
19
+ binomial_coefficients_list, multinomial_coefficients
20
+ """
21
+ n = as_int(n)
22
+ d = {(0, n): 1, (n, 0): 1}
23
+ a = 1
24
+ for k in range(1, n//2 + 1):
25
+ a = (a * (n - k + 1))//k
26
+ d[k, n - k] = d[n - k, k] = a
27
+ return d
28
+
29
+
30
+ def binomial_coefficients_list(n):
31
+ """ Return a list of binomial coefficients as rows of the Pascal's
32
+ triangle.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy.ntheory import binomial_coefficients_list
38
+ >>> binomial_coefficients_list(9)
39
+ [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
40
+
41
+ See Also
42
+ ========
43
+
44
+ binomial_coefficients, multinomial_coefficients
45
+ """
46
+ n = as_int(n)
47
+ d = [1] * (n + 1)
48
+ a = 1
49
+ for k in range(1, n//2 + 1):
50
+ a = (a * (n - k + 1))//k
51
+ d[k] = d[n - k] = a
52
+ return d
53
+
54
+
55
+ def multinomial_coefficients(m, n):
56
+ r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
57
+ where ``C_kn`` are multinomial coefficients such that
58
+ ``n=k1+k2+..+km``.
59
+
60
+ Examples
61
+ ========
62
+
63
+ >>> from sympy.ntheory import multinomial_coefficients
64
+ >>> multinomial_coefficients(2, 5) # indirect doctest
65
+ {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
66
+
67
+ Notes
68
+ =====
69
+
70
+ The algorithm is based on the following result:
71
+
72
+ .. math::
73
+ \binom{n}{k_1, \ldots, k_m} =
74
+ \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
75
+
76
+ Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
77
+ of the author.
78
+
79
+ See Also
80
+ ========
81
+
82
+ binomial_coefficients_list, binomial_coefficients
83
+ """
84
+ m = as_int(m)
85
+ n = as_int(n)
86
+ if not m:
87
+ if n:
88
+ return {}
89
+ return {(): 1}
90
+ if m == 2:
91
+ return binomial_coefficients(n)
92
+ if m >= 2*n and n > 1:
93
+ return dict(multinomial_coefficients_iterator(m, n))
94
+ t = [n] + [0] * (m - 1)
95
+ r = {tuple(t): 1}
96
+ if n:
97
+ j = 0 # j will be the leftmost nonzero position
98
+ else:
99
+ j = m
100
+ # enumerate tuples in co-lex order
101
+ while j < m - 1:
102
+ # compute next tuple
103
+ tj = t[j]
104
+ if j:
105
+ t[j] = 0
106
+ t[0] = tj
107
+ if tj > 1:
108
+ t[j + 1] += 1
109
+ j = 0
110
+ start = 1
111
+ v = 0
112
+ else:
113
+ j += 1
114
+ start = j + 1
115
+ v = r[tuple(t)]
116
+ t[j] += 1
117
+ # compute the value
118
+ # NB: the initialization of v was done above
119
+ for k in range(start, m):
120
+ if t[k]:
121
+ t[k] -= 1
122
+ v += r[tuple(t)]
123
+ t[k] += 1
124
+ t[0] -= 1
125
+ r[tuple(t)] = (v * tj) // (n - t[0])
126
+ return r
127
+
128
+
129
+ def multinomial_coefficients_iterator(m, n, _tuple=tuple):
130
+ """multinomial coefficient iterator
131
+
132
+ This routine has been optimized for `m` large with respect to `n` by taking
133
+ advantage of the fact that when the monomial tuples `t` are stripped of
134
+ zeros, their coefficient is the same as that of the monomial tuples from
135
+ ``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
136
+ precomputed to save memory and time.
137
+
138
+ >>> from sympy.ntheory.multinomial import multinomial_coefficients
139
+ >>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
140
+ >>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
141
+ True
142
+
143
+ Examples
144
+ ========
145
+
146
+ >>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
147
+ >>> it = multinomial_coefficients_iterator(20,3)
148
+ >>> next(it)
149
+ ((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
150
+ """
151
+ m = as_int(m)
152
+ n = as_int(n)
153
+ if m < 2*n or n == 1:
154
+ mc = multinomial_coefficients(m, n)
155
+ yield from mc.items()
156
+ else:
157
+ mc = multinomial_coefficients(n, n)
158
+ mc1 = {}
159
+ for k, v in mc.items():
160
+ mc1[_tuple(filter(None, k))] = v
161
+ mc = mc1
162
+
163
+ t = [n] + [0] * (m - 1)
164
+ t1 = _tuple(t)
165
+ b = _tuple(filter(None, t1))
166
+ yield (t1, mc[b])
167
+ if n:
168
+ j = 0 # j will be the leftmost nonzero position
169
+ else:
170
+ j = m
171
+ # enumerate tuples in co-lex order
172
+ while j < m - 1:
173
+ # compute next tuple
174
+ tj = t[j]
175
+ if j:
176
+ t[j] = 0
177
+ t[0] = tj
178
+ if tj > 1:
179
+ t[j + 1] += 1
180
+ j = 0
181
+ else:
182
+ j += 1
183
+ t[j] += 1
184
+
185
+ t[0] -= 1
186
+ t1 = _tuple(t)
187
+ b = _tuple(filter(None, t1))
188
+ yield (t1, mc[b])
.venv/Lib/site-packages/sympy/ntheory/partitions_.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mpmath.libmp import (fzero, from_int, from_rational,
2
+ fone, fhalf, bitcount, to_int, mpf_mul, mpf_div, mpf_sub,
3
+ mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
4
+ from .residue_ntheory import _sqrt_mod_prime_power, is_quad_residue
5
+ from sympy.utilities.decorator import deprecated
6
+ from sympy.utilities.memoization import recurrence_memo
7
+
8
+ import math
9
+ from itertools import count
10
+
11
+ def _pre():
12
+ maxn = 10**5
13
+ global _factor, _totient
14
+ _factor = [0]*maxn
15
+ _totient = [1]*maxn
16
+ lim = int(maxn**0.5) + 5
17
+ for i in range(2, lim):
18
+ if _factor[i] == 0:
19
+ for j in range(i*i, maxn, i):
20
+ if _factor[j] == 0:
21
+ _factor[j] = i
22
+ for i in range(2, maxn):
23
+ if _factor[i] == 0:
24
+ _factor[i] = i
25
+ _totient[i] = i-1
26
+ continue
27
+ x = _factor[i]
28
+ y = i//x
29
+ if y % x == 0:
30
+ _totient[i] = _totient[y]*x
31
+ else:
32
+ _totient[i] = _totient[y]*(x - 1)
33
+
34
+ def _a(n, k, prec):
35
+ """ Compute the inner sum in HRR formula [1]_
36
+
37
+ References
38
+ ==========
39
+
40
+ .. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
41
+
42
+ """
43
+ if k == 1:
44
+ return fone
45
+
46
+ k1 = k
47
+ e = 0
48
+ p = _factor[k]
49
+ while k1 % p == 0:
50
+ k1 //= p
51
+ e += 1
52
+ k2 = k//k1 # k2 = p^e
53
+ v = 1 - 24*n
54
+ pi = mpf_pi(prec)
55
+
56
+ if k1 == 1:
57
+ # k = p^e
58
+ if p == 2:
59
+ mod = 8*k
60
+ v = mod + v % mod
61
+ v = (v*pow(9, k - 1, mod)) % mod
62
+ m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
63
+ arg = mpf_div(mpf_mul(
64
+ from_int(4*m), pi, prec), from_int(mod), prec)
65
+ return mpf_mul(mpf_mul(
66
+ from_int((-1)**e*(2 - (m % 4))),
67
+ mpf_sqrt(from_int(k), prec), prec),
68
+ mpf_sin(arg, prec), prec)
69
+ if p == 3:
70
+ mod = 3*k
71
+ v = mod + v % mod
72
+ if e > 1:
73
+ v = (v*pow(64, k//3 - 1, mod)) % mod
74
+ m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
75
+ arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
76
+ from_int(mod), prec)
77
+ return mpf_mul(mpf_mul(
78
+ from_int(2*(-1)**(e + 1)*(3 - 2*(m % 3))),
79
+ mpf_sqrt(from_int(k//3), prec), prec),
80
+ mpf_sin(arg, prec), prec)
81
+ v = k + v % k
82
+ jacobi3 = -1 if k % 12 in [5, 7] else 1
83
+ if v % p == 0:
84
+ if e == 1:
85
+ return mpf_mul(
86
+ from_int(jacobi3),
87
+ mpf_sqrt(from_int(k), prec), prec)
88
+ return fzero
89
+ if not is_quad_residue(v, p):
90
+ return fzero
91
+ _phi = p**(e - 1)*(p - 1)
92
+ v = (v*pow(576, _phi - 1, k))
93
+ m = _sqrt_mod_prime_power(v, p, e)[0]
94
+ arg = mpf_div(
95
+ mpf_mul(from_int(4*m), pi, prec),
96
+ from_int(k), prec)
97
+ return mpf_mul(mpf_mul(
98
+ from_int(2*jacobi3),
99
+ mpf_sqrt(from_int(k), prec), prec),
100
+ mpf_cos(arg, prec), prec)
101
+
102
+ if p != 2 or e >= 3:
103
+ d1, d2 = math.gcd(k1, 24), math.gcd(k2, 24)
104
+ e = 24//(d1*d2)
105
+ n1 = ((d2*e*n + (k2**2 - 1)//d1)*
106
+ pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
107
+ n2 = ((d1*e*n + (k1**2 - 1)//d2)*
108
+ pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
109
+ return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
110
+ if e == 2:
111
+ n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
112
+ n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
113
+ return mpf_mul(mpf_mul(
114
+ from_int(-1),
115
+ _a(n1, k1, prec), prec),
116
+ _a(n2, k2, prec))
117
+ n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
118
+ n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
119
+ return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
120
+
121
+ def _d(n, j, prec, sq23pi, sqrt8):
122
+ """
123
+ Compute the sinh term in the outer sum of the HRR formula.
124
+ The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
125
+ """
126
+ j = from_int(j)
127
+ pi = mpf_pi(prec)
128
+ a = mpf_div(sq23pi, j, prec)
129
+ b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
130
+ c = mpf_sqrt(b, prec)
131
+ ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
132
+ D = mpf_div(
133
+ mpf_sqrt(j, prec),
134
+ mpf_mul(mpf_mul(sqrt8, b), pi), prec)
135
+ E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
136
+ return mpf_mul(D, E)
137
+
138
+
139
+ @recurrence_memo([1, 1])
140
+ def _partition_rec(n: int, prev) -> int:
141
+ """ Calculate the partition function P(n)
142
+
143
+ Parameters
144
+ ==========
145
+
146
+ n : int
147
+ nonnegative integer
148
+
149
+ """
150
+ v = 0
151
+ penta = 0 # pentagonal number: 1, 5, 12, ...
152
+ for i in count():
153
+ penta += 3*i + 1
154
+ np = n - penta
155
+ if np < 0:
156
+ break
157
+ s = prev[np]
158
+ np -= i + 1
159
+ # np = n - gp where gp = generalized pentagonal: 2, 7, 15, ...
160
+ if 0 <= np:
161
+ s += prev[np]
162
+ v += -s if i % 2 else s
163
+ return v
164
+
165
+
166
+ def _partition(n: int) -> int:
167
+ """ Calculate the partition function P(n)
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ n : int
173
+
174
+ """
175
+ if n < 0:
176
+ return 0
177
+ if (n <= 200_000 and n - _partition_rec.cache_length() < 70 or
178
+ _partition_rec.cache_length() == 2 and n < 14_400):
179
+ # There will be 2*10**5 elements created here
180
+ # and n elements created by partition, so in case we
181
+ # are going to be working with small n, we just
182
+ # use partition to calculate (and cache) the values
183
+ # since lookup is used there while summation, using
184
+ # _factor and _totient, will be used below. But we
185
+ # only do so if n is relatively close to the length
186
+ # of the cache since doing 1 calculation here is about
187
+ # the same as adding 70 elements to the cache. In addition,
188
+ # the startup here costs about the same as calculating the first
189
+ # 14,400 values via partition, so we delay startup here unless n
190
+ # is smaller than that.
191
+ return _partition_rec(n)
192
+ if '_factor' not in globals():
193
+ _pre()
194
+ # Estimate number of bits in p(n). This formula could be tidied
195
+ pbits = int((
196
+ math.pi*(2*n/3.)**0.5 -
197
+ math.log(4*n))/math.log(10) + 1) * \
198
+ math.log2(10)
199
+ prec = p = int(pbits*1.1 + 100)
200
+
201
+ # find the number of terms needed so rounded sum will be accurate
202
+ # using Rademacher's bound M(n, N) for the remainder after a partial
203
+ # sum of N terms (https://arxiv.org/pdf/1205.5991.pdf, (1.8))
204
+ c1 = 44*math.pi**2/(225*math.sqrt(3))
205
+ c2 = math.pi*math.sqrt(2)/75
206
+ c3 = math.pi*math.sqrt(2/3)
207
+ def _M(n, N):
208
+ sqrt = math.sqrt
209
+ return c1/sqrt(N) + c2*sqrt(N/(n - 1))*math.sinh(c3*sqrt(n)/N)
210
+ big = max(9, math.ceil(n**0.5)) # should be too large (for n > 65, ceil should work)
211
+ assert _M(n, big) < 0.5 # else double big until too large
212
+ while big > 40 and _M(n, big) < 0.5:
213
+ big //= 2
214
+ small = big
215
+ big = small*2
216
+ while big - small > 1:
217
+ N = (big + small)//2
218
+ if (er := _M(n, N)) < 0.5:
219
+ big = N
220
+ elif er >= 0.5:
221
+ small = N
222
+ M = big # done with function M; now have value
223
+
224
+ # sanity check for expected size of answer
225
+ if M > 10**5: # i.e. M > maxn
226
+ raise ValueError("Input too big") # i.e. n > 149832547102
227
+
228
+ # calculate it
229
+ s = fzero
230
+ sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
231
+ sqrt8 = mpf_sqrt(from_int(8), p)
232
+ for q in range(1, M):
233
+ a = _a(n, q, p)
234
+ d = _d(n, q, p, sq23pi, sqrt8)
235
+ s = mpf_add(s, mpf_mul(a, d), prec)
236
+ # On average, the terms decrease rapidly in magnitude.
237
+ # Dynamically reducing the precision greatly improves
238
+ # performance.
239
+ p = bitcount(abs(to_int(d))) + 50
240
+ return int(to_int(mpf_add(s, fhalf, prec)))
241
+
242
+
243
+ @deprecated("""\
244
+ The `sympy.ntheory.partitions_.npartitions` has been moved to `sympy.functions.combinatorial.numbers.partition`.""",
245
+ deprecated_since_version="1.13",
246
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
247
+ def npartitions(n, verbose=False):
248
+ """
249
+ Calculate the partition function P(n), i.e. the number of ways that
250
+ n can be written as a sum of positive integers.
251
+
252
+ .. deprecated:: 1.13
253
+
254
+ The ``npartitions`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.partition`
255
+ instead. See its documentation for more information. See
256
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
257
+
258
+ P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
259
+
260
+
261
+ The correctness of this implementation has been tested through $10^{10}$.
262
+
263
+ Examples
264
+ ========
265
+
266
+ >>> from sympy.functions.combinatorial.numbers import partition
267
+ >>> partition(25)
268
+ 1958
269
+
270
+ References
271
+ ==========
272
+
273
+ .. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
274
+
275
+ """
276
+ from sympy.functions.combinatorial.numbers import partition as func_partition
277
+ return func_partition(n)
.venv/Lib/site-packages/sympy/ntheory/primetest.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Primality testing
3
+
4
+ """
5
+
6
+ from itertools import count
7
+
8
+ from sympy.core.sympify import sympify
9
+ from sympy.external.gmpy import (gmpy as _gmpy, gcd, jacobi,
10
+ is_square as gmpy_is_square,
11
+ bit_scan1, is_fermat_prp, is_euler_prp,
12
+ is_selfridge_prp, is_strong_selfridge_prp,
13
+ is_strong_bpsw_prp)
14
+ from sympy.external.ntheory import _lucas_sequence
15
+ from sympy.utilities.misc import as_int, filldedent
16
+
17
+ # Note: This list should be updated whenever new Mersenne primes are found.
18
+ # Refer: https://www.mersenne.org/
19
+ MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
20
+ 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
21
+ 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
22
+ 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933,
23
+ 136279841)
24
+
25
+
26
+ def is_fermat_pseudoprime(n, a):
27
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
28
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
29
+
30
+ .. math ::
31
+ a^{n-1} \equiv 1 \pmod{n}
32
+
33
+ (where mod refers to the modulo operation).
34
+
35
+ Parameters
36
+ ==========
37
+
38
+ n : Integer
39
+ ``n`` is a positive integer.
40
+ a : Integer
41
+ ``a`` is a positive integer.
42
+ ``a`` and ``n`` should be relatively prime.
43
+
44
+ Returns
45
+ =======
46
+
47
+ bool : If ``n`` is prime, it always returns ``True``.
48
+ The composite number that returns ``True`` is called an Fermat pseudoprime.
49
+
50
+ Examples
51
+ ========
52
+
53
+ >>> from sympy.ntheory.primetest import is_fermat_pseudoprime
54
+ >>> from sympy.ntheory.factor_ import isprime
55
+ >>> for n in range(1, 1000):
56
+ ... if is_fermat_pseudoprime(n, 2) and not isprime(n):
57
+ ... print(n)
58
+ 341
59
+ 561
60
+ 645
61
+
62
+ References
63
+ ==========
64
+
65
+ .. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
66
+ """
67
+ n, a = as_int(n), as_int(a)
68
+ if a == 1:
69
+ return n == 2 or bool(n % 2)
70
+ return is_fermat_prp(n, a)
71
+
72
+
73
+ def is_euler_pseudoprime(n, a):
74
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
75
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
76
+
77
+ .. math ::
78
+ a^{(n-1)/2} \equiv \pm 1 \pmod{n}
79
+
80
+ (where mod refers to the modulo operation).
81
+
82
+ Parameters
83
+ ==========
84
+
85
+ n : Integer
86
+ ``n`` is a positive integer.
87
+ a : Integer
88
+ ``a`` is a positive integer.
89
+ ``a`` and ``n`` should be relatively prime.
90
+
91
+ Returns
92
+ =======
93
+
94
+ bool : If ``n`` is prime, it always returns ``True``.
95
+ The composite number that returns ``True`` is called an Euler pseudoprime.
96
+
97
+ Examples
98
+ ========
99
+
100
+ >>> from sympy.ntheory.primetest import is_euler_pseudoprime
101
+ >>> from sympy.ntheory.factor_ import isprime
102
+ >>> for n in range(1, 1000):
103
+ ... if is_euler_pseudoprime(n, 2) and not isprime(n):
104
+ ... print(n)
105
+ 341
106
+ 561
107
+
108
+ References
109
+ ==========
110
+
111
+ .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
112
+ """
113
+ n, a = as_int(n), as_int(a)
114
+ if a < 1:
115
+ raise ValueError("a should be an integer greater than 0")
116
+ if n < 1:
117
+ raise ValueError("n should be an integer greater than 0")
118
+ if n == 1:
119
+ return False
120
+ if a == 1:
121
+ return n == 2 or bool(n % 2) # (prime or odd composite)
122
+ if n % 2 == 0:
123
+ return n == 2
124
+ if gcd(n, a) != 1:
125
+ raise ValueError("The two numbers should be relatively prime")
126
+ return pow(a, (n - 1) // 2, n) in [1, n - 1]
127
+
128
+
129
+ def is_euler_jacobi_pseudoprime(n, a):
130
+ r"""Returns True if ``n`` is prime or is an odd composite integer that
131
+ is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
132
+
133
+ .. math ::
134
+ a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}
135
+
136
+ (where mod refers to the modulo operation).
137
+
138
+ Parameters
139
+ ==========
140
+
141
+ n : Integer
142
+ ``n`` is a positive integer.
143
+ a : Integer
144
+ ``a`` is a positive integer.
145
+ ``a`` and ``n`` should be relatively prime.
146
+
147
+ Returns
148
+ =======
149
+
150
+ bool : If ``n`` is prime, it always returns ``True``.
151
+ The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.
152
+
153
+ Examples
154
+ ========
155
+
156
+ >>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
157
+ >>> from sympy.ntheory.factor_ import isprime
158
+ >>> for n in range(1, 1000):
159
+ ... if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
160
+ ... print(n)
161
+ 561
162
+
163
+ References
164
+ ==========
165
+
166
+ .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
167
+ """
168
+ n, a = as_int(n), as_int(a)
169
+ if a == 1:
170
+ return n == 2 or bool(n % 2)
171
+ return is_euler_prp(n, a)
172
+
173
+
174
+ def is_square(n, prep=True):
175
+ """Return True if n == a * a for some integer a, else False.
176
+ If n is suspected of *not* being a square then this is a
177
+ quick method of confirming that it is not.
178
+
179
+ Examples
180
+ ========
181
+
182
+ >>> from sympy.ntheory.primetest import is_square
183
+ >>> is_square(25)
184
+ True
185
+ >>> is_square(2)
186
+ False
187
+
188
+ References
189
+ ==========
190
+
191
+ .. [1] https://mersenneforum.org/showpost.php?p=110896
192
+
193
+ See Also
194
+ ========
195
+ sympy.core.intfunc.isqrt
196
+ """
197
+ if prep:
198
+ n = as_int(n)
199
+ if n < 0:
200
+ return False
201
+ if n in (0, 1):
202
+ return True
203
+ return gmpy_is_square(n)
204
+
205
+
206
+ def _test(n, base, s, t):
207
+ """Miller-Rabin strong pseudoprime test for one base.
208
+ Return False if n is definitely composite, True if n is
209
+ probably prime, with a probability greater than 3/4.
210
+
211
+ """
212
+ # do the Fermat test
213
+ b = pow(base, t, n)
214
+ if b == 1 or b == n - 1:
215
+ return True
216
+ for _ in range(s - 1):
217
+ b = pow(b, 2, n)
218
+ if b == n - 1:
219
+ return True
220
+ # see I. Niven et al. "An Introduction to Theory of Numbers", page 78
221
+ if b == 1:
222
+ return False
223
+ return False
224
+
225
+
226
+ def mr(n, bases):
227
+ """Perform a Miller-Rabin strong pseudoprime test on n using a
228
+ given list of bases/witnesses.
229
+
230
+ References
231
+ ==========
232
+
233
+ .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
234
+ A Computational Perspective", Springer, 2nd edition, 135-138
235
+
236
+ A list of thresholds and the bases they require are here:
237
+ https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy.ntheory.primetest import mr
243
+ >>> mr(1373651, [2, 3])
244
+ False
245
+ >>> mr(479001599, [31, 73])
246
+ True
247
+
248
+ """
249
+ from sympy.polys.domains import ZZ
250
+
251
+ n = as_int(n)
252
+ if n < 2 or (n > 2 and n % 2 == 0):
253
+ return False
254
+ # remove powers of 2 from n-1 (= t * 2**s)
255
+ s = bit_scan1(n - 1)
256
+ t = n >> s
257
+ for base in bases:
258
+ # Bases >= n are wrapped, bases < 2 are invalid
259
+ if base >= n:
260
+ base %= n
261
+ if base >= 2:
262
+ base = ZZ(base)
263
+ if not _test(n, base, s, t):
264
+ return False
265
+ return True
266
+
267
+
268
+ def _lucas_extrastrong_params(n):
269
+ """Calculates the "extra strong" parameters (D, P, Q) for n.
270
+
271
+ Parameters
272
+ ==========
273
+
274
+ n : int
275
+ positive odd integer
276
+
277
+ Returns
278
+ =======
279
+
280
+ D, P, Q: "extra strong" parameters.
281
+ ``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy.ntheory.primetest import _lucas_extrastrong_params
287
+ >>> _lucas_extrastrong_params(101)
288
+ (12, 4, 1)
289
+ >>> _lucas_extrastrong_params(15)
290
+ (0, 0, 0)
291
+
292
+ References
293
+ ==========
294
+ .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
295
+ https://oeis.org/A217719
296
+ .. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime
297
+
298
+ """
299
+ for P in count(3):
300
+ D = P**2 - 4
301
+ j = jacobi(D, n)
302
+ if j == -1:
303
+ return (D, P, 1)
304
+ elif j == 0 and D % n:
305
+ return (0, 0, 0)
306
+
307
+
308
+ def is_lucas_prp(n):
309
+ """Standard Lucas compositeness test with Selfridge parameters. Returns
310
+ False if n is definitely composite, and True if n is a Lucas probable
311
+ prime.
312
+
313
+ This is typically used in combination with the Miller-Rabin test.
314
+
315
+ References
316
+ ==========
317
+ .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
318
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
319
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
320
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
321
+ .. [2] OEIS A217120: Lucas Pseudoprimes
322
+ https://oeis.org/A217120
323
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
329
+ >>> for i in range(10000):
330
+ ... if is_lucas_prp(i) and not isprime(i):
331
+ ... print(i)
332
+ 323
333
+ 377
334
+ 1159
335
+ 1829
336
+ 3827
337
+ 5459
338
+ 5777
339
+ 9071
340
+ 9179
341
+ """
342
+ n = as_int(n)
343
+ if n < 2:
344
+ return False
345
+ return is_selfridge_prp(n)
346
+
347
+
348
+ def is_strong_lucas_prp(n):
349
+ """Strong Lucas compositeness test with Selfridge parameters. Returns
350
+ False if n is definitely composite, and True if n is a strong Lucas
351
+ probable prime.
352
+
353
+ This is often used in combination with the Miller-Rabin test, and
354
+ in particular, when combined with M-R base 2 creates the strong BPSW test.
355
+
356
+ References
357
+ ==========
358
+ .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
359
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
360
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
361
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
362
+ .. [2] OEIS A217255: Strong Lucas Pseudoprimes
363
+ https://oeis.org/A217255
364
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
365
+ .. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
366
+
367
+ Examples
368
+ ========
369
+
370
+ >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
371
+ >>> for i in range(20000):
372
+ ... if is_strong_lucas_prp(i) and not isprime(i):
373
+ ... print(i)
374
+ 5459
375
+ 5777
376
+ 10877
377
+ 16109
378
+ 18971
379
+ """
380
+ n = as_int(n)
381
+ if n < 2:
382
+ return False
383
+ return is_strong_selfridge_prp(n)
384
+
385
+
386
+ def is_extra_strong_lucas_prp(n):
387
+ """Extra Strong Lucas compositeness test. Returns False if n is
388
+ definitely composite, and True if n is an "extra strong" Lucas probable
389
+ prime.
390
+
391
+ The parameters are selected using P = 3, Q = 1, then incrementing P until
392
+ (D|n) == -1. The test itself is as defined in [1]_, from the
393
+ Mo and Jones preprint. The parameter selection and test are the same as
394
+ used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
395
+ page on Wikipedia.
396
+
397
+ It is 20-50% faster than the strong test.
398
+
399
+ Because of the different parameters selected, there is no relationship
400
+ between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
401
+ In particular, one is not a subset of the other.
402
+
403
+ References
404
+ ==========
405
+ .. [1] Jon Grantham, Frobenius Pseudoprimes,
406
+ Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
407
+ https://doi.org/10.1090%2FS0025-5718-00-01197-2
408
+ .. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
409
+ https://oeis.org/A217719
410
+ .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
411
+
412
+ Examples
413
+ ========
414
+
415
+ >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
416
+ >>> for i in range(20000):
417
+ ... if is_extra_strong_lucas_prp(i) and not isprime(i):
418
+ ... print(i)
419
+ 989
420
+ 3239
421
+ 5777
422
+ 10877
423
+ """
424
+ # Implementation notes:
425
+ # 1) the parameters differ from Thomas R. Nicely's. His parameter
426
+ # selection leads to pseudoprimes that overlap M-R tests, and
427
+ # contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
428
+ # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
429
+ # sequence must have Q=1. See Grantham theorem 2.3, any of the
430
+ # references on the MathWorld page, or run it and see Q=-1 is wrong.
431
+ n = as_int(n)
432
+ if n == 2:
433
+ return True
434
+ if n < 2 or (n % 2) == 0:
435
+ return False
436
+ if gmpy_is_square(n):
437
+ return False
438
+
439
+ D, P, Q = _lucas_extrastrong_params(n)
440
+ if D == 0:
441
+ return False
442
+
443
+ # remove powers of 2 from n+1 (= k * 2**s)
444
+ s = bit_scan1(n + 1)
445
+ k = (n + 1) >> s
446
+
447
+ U, V, _ = _lucas_sequence(n, P, Q, k)
448
+
449
+ if U == 0 and (V == 2 or V == n - 2):
450
+ return True
451
+ for _ in range(1, s):
452
+ if V == 0:
453
+ return True
454
+ V = (V*V - 2) % n
455
+ return False
456
+
457
+
458
+ def proth_test(n):
459
+ r""" Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.
460
+
461
+ Parameters
462
+ ==========
463
+
464
+ n : Integer
465
+ ``n`` is Proth number
466
+
467
+ Returns
468
+ =======
469
+
470
+ bool : If ``True``, then ``n`` is the Proth prime
471
+
472
+ Raises
473
+ ======
474
+
475
+ ValueError
476
+ If ``n`` is not Proth number.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy.ntheory.primetest import proth_test
482
+ >>> proth_test(41)
483
+ True
484
+ >>> proth_test(57)
485
+ False
486
+
487
+ References
488
+ ==========
489
+
490
+ .. [1] https://en.wikipedia.org/wiki/Proth_prime
491
+
492
+ """
493
+ n = as_int(n)
494
+ if n < 3:
495
+ raise ValueError("n is not Proth number")
496
+ m = bit_scan1(n - 1)
497
+ k = n >> m
498
+ if m < k.bit_length():
499
+ raise ValueError("n is not Proth number")
500
+ if n % 3 == 0:
501
+ return n == 3
502
+ if k % 3: # n % 12 == 5
503
+ return pow(3, n >> 1, n) == n - 1
504
+ # If `n` is a square number, then `jacobi(a, n) = 1` for any `a`
505
+ if gmpy_is_square(n):
506
+ return False
507
+ # `a` may be chosen at random.
508
+ # In any case, we want to find `a` such that `jacobi(a, n) = -1`.
509
+ for a in range(5, n):
510
+ j = jacobi(a, n)
511
+ if j == -1:
512
+ return pow(a, n >> 1, n) == n - 1
513
+ if j == 0:
514
+ return False
515
+
516
+
517
+ def _lucas_lehmer_primality_test(p):
518
+ r""" Test if the Mersenne number `M_p = 2^p-1` is prime.
519
+
520
+ Parameters
521
+ ==========
522
+
523
+ p : int
524
+ ``p`` is an odd prime number
525
+
526
+ Returns
527
+ =======
528
+
529
+ bool : If ``True``, then `M_p` is the Mersenne prime
530
+
531
+ Examples
532
+ ========
533
+
534
+ >>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
535
+ >>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
536
+ True
537
+ >>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
538
+ False
539
+
540
+ See Also
541
+ ========
542
+
543
+ is_mersenne_prime
544
+
545
+ References
546
+ ==========
547
+
548
+ .. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
549
+
550
+ """
551
+ v = 4
552
+ m = 2**p - 1
553
+ for _ in range(p - 2):
554
+ v = pow(v, 2, m) - 2
555
+ return v == 0
556
+
557
+
558
+ def is_mersenne_prime(n):
559
+ """Returns True if ``n`` is a Mersenne prime, else False.
560
+
561
+ A Mersenne prime is a prime number having the form `2^i - 1`.
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy.ntheory.factor_ import is_mersenne_prime
567
+ >>> is_mersenne_prime(6)
568
+ False
569
+ >>> is_mersenne_prime(127)
570
+ True
571
+
572
+ References
573
+ ==========
574
+
575
+ .. [1] https://mathworld.wolfram.com/MersennePrime.html
576
+
577
+ """
578
+ n = as_int(n)
579
+ if n < 1:
580
+ return False
581
+ if n & (n + 1):
582
+ # n is not Mersenne number
583
+ return False
584
+ p = n.bit_length()
585
+ if p in MERSENNE_PRIME_EXPONENTS:
586
+ return True
587
+ if p < 65_000_000 or not isprime(p):
588
+ # According to GIMPS, verification was completed on September 19, 2023 for p less than 65 million.
589
+ # https://www.mersenne.org/report_milestones/
590
+ # If p is composite number, then n=2**p-1 is composite number.
591
+ return False
592
+ result = _lucas_lehmer_primality_test(p)
593
+ if result:
594
+ raise ValueError(filldedent('''
595
+ This Mersenne Prime, 2^%s - 1, should
596
+ be added to SymPy's known values.''' % p))
597
+ return result
598
+
599
+
600
+ _MR_BASES_32 = [15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295,
601
+ 2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471,
602
+ 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763,
603
+ 4852, 5012, 3185, 1333, 6227,5298, 1074, 2391, 5113, 7061,
604
+ 803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556,
605
+ 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373,
606
+ 6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467,
607
+ 3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888,
608
+ 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875,
609
+ 3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165,
610
+ 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377,
611
+ 1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601,
612
+ 6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360,
613
+ 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031,
614
+ 2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725,
615
+ 3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371,
616
+ 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727,
617
+ 3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126,
618
+ 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674,
619
+ 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007,
620
+ 35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521,
621
+ 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166,
622
+ 1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197,
623
+ 13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449,
624
+ 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194]
625
+
626
+
627
+ def isprime(n):
628
+ """
629
+ Test if n is a prime number (True) or not (False). For n < 2^64 the
630
+ answer is definitive; larger n values have a small probability of actually
631
+ being pseudoprimes.
632
+
633
+ Negative numbers (e.g. -2) are not considered prime.
634
+
635
+ The first step is looking for trivial factors, which if found enables
636
+ a quick return. Next, if the sieve is large enough, use bisection search
637
+ on the sieve. For small numbers, a set of deterministic Miller-Rabin
638
+ tests are performed with bases that are known to have no counterexamples
639
+ in their range. Finally if the number is larger than 2^64, a strong
640
+ BPSW test is performed. While this is a probable prime test and we
641
+ believe counterexamples exist, there are no known counterexamples.
642
+
643
+ Examples
644
+ ========
645
+
646
+ >>> from sympy.ntheory import isprime
647
+ >>> isprime(13)
648
+ True
649
+ >>> isprime(15)
650
+ False
651
+
652
+ Notes
653
+ =====
654
+
655
+ This routine is intended only for integer input, not numerical
656
+ expressions which may represent numbers. Floats are also
657
+ rejected as input because they represent numbers of limited
658
+ precision. While it is tempting to permit 7.0 to represent an
659
+ integer there are errors that may "pass silently" if this is
660
+ allowed:
661
+
662
+ >>> from sympy import Float, S
663
+ >>> int(1e3) == 1e3 == 10**3
664
+ True
665
+ >>> int(1e23) == 1e23
666
+ True
667
+ >>> int(1e23) == 10**23
668
+ False
669
+
670
+ >>> near_int = 1 + S(1)/10**19
671
+ >>> near_int == int(near_int)
672
+ False
673
+ >>> n = Float(near_int, 10) # truncated by precision
674
+ >>> n % 1 == 0
675
+ True
676
+ >>> n = Float(near_int, 20)
677
+ >>> n % 1 == 0
678
+ False
679
+
680
+ See Also
681
+ ========
682
+
683
+ sympy.ntheory.generate.primerange : Generates all primes in a given range
684
+ sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
685
+ sympy.ntheory.generate.prime : Return the nth prime
686
+
687
+ References
688
+ ==========
689
+ .. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
690
+ .. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
691
+ Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
692
+ https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
693
+ http://mpqs.free.fr/LucasPseudoprimes.pdf
694
+ .. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
695
+ """
696
+ n = as_int(n)
697
+
698
+ # Step 1, do quick composite testing via trial division. The individual
699
+ # modulo tests benchmark faster than one or two primorial igcds for me.
700
+ # The point here is just to speedily handle small numbers and many
701
+ # composites. Step 2 only requires that n <= 2 get handled here.
702
+ if n in [2, 3, 5]:
703
+ return True
704
+ if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
705
+ return False
706
+ if n < 49:
707
+ return True
708
+ if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
709
+ (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
710
+ (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
711
+ return False
712
+ if n < 2809:
713
+ return True
714
+ if n < 65077:
715
+ # There are only five Euler pseudoprimes with a least prime factor greater than 47
716
+ return pow(2, n >> 1, n) in [1, n - 1] and n not in [8321, 31621, 42799, 49141, 49981]
717
+
718
+ # bisection search on the sieve if the sieve is large enough
719
+ from sympy.ntheory.generate import sieve as s
720
+ if n <= s._list[-1]:
721
+ l, u = s.search(n)
722
+ return l == u
723
+ from sympy.ntheory.factor_ import factor_cache
724
+ if (ret := factor_cache.get(n)) is not None:
725
+ return ret == n
726
+
727
+ # If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
728
+ # This should be a bit faster than our step 2, and for large values will
729
+ # be a lot faster than our step 3 (C+GMP vs. Python).
730
+ if _gmpy is not None:
731
+ return is_strong_bpsw_prp(n)
732
+
733
+
734
+ # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
735
+ # https://miller-rabin.appspot.com/
736
+ # for lists. We have made sure the M-R routine will successfully handle
737
+ # bases larger than n, so we can use the minimal set.
738
+ # In September 2015 deterministic numbers were extended to over 2^81.
739
+ # https://arxiv.org/pdf/1509.00864.pdf
740
+ # https://oeis.org/A014233
741
+ if n < 341531:
742
+ return mr(n, [9345883071009581737])
743
+ if n < 4296595241:
744
+ # Michal Forisek and Jakub Jancina,
745
+ # Fast Primality Testing for Integers That Fit into a Machine Word
746
+ # https://ceur-ws.org/Vol-1326/020-Forisek.pdf
747
+ h = ((n >> 16) ^ n) * 0x45d9f3b
748
+ h = ((h >> 16) ^ h) * 0x45d9f3b
749
+ h = ((h >> 16) ^ h) & 255
750
+ return mr(n, [_MR_BASES_32[h]])
751
+ if n < 350269456337:
752
+ return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
753
+ if n < 55245642489451:
754
+ return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
755
+ if n < 7999252175582851:
756
+ return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
757
+ if n < 585226005592931977:
758
+ return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
759
+ if n < 18446744073709551616:
760
+ return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
761
+ if n < 318665857834031151167461:
762
+ return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
763
+ if n < 3317044064679887385961981:
764
+ return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
765
+
766
+ # We could do this instead at any point:
767
+ #if n < 18446744073709551616:
768
+ # return mr(n, [2]) and is_extra_strong_lucas_prp(n)
769
+
770
+ # Here are tests that are safe for MR routines that don't understand
771
+ # large bases.
772
+ #if n < 9080191:
773
+ # return mr(n, [31, 73])
774
+ #if n < 19471033:
775
+ # return mr(n, [2, 299417])
776
+ #if n < 38010307:
777
+ # return mr(n, [2, 9332593])
778
+ #if n < 316349281:
779
+ # return mr(n, [11000544, 31481107])
780
+ #if n < 4759123141:
781
+ # return mr(n, [2, 7, 61])
782
+ #if n < 105936894253:
783
+ # return mr(n, [2, 1005905886, 1340600841])
784
+ #if n < 31858317218647:
785
+ # return mr(n, [2, 642735, 553174392, 3046413974])
786
+ #if n < 3071837692357849:
787
+ # return mr(n, [2, 75088, 642735, 203659041, 3613982119])
788
+ #if n < 18446744073709551616:
789
+ # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
790
+
791
+ # Step 3: BPSW.
792
+ #
793
+ # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
794
+ # 44.0s old isprime using 46 bases
795
+ # 5.3s strong BPSW + one random base
796
+ # 4.3s extra strong BPSW + one random base
797
+ # 4.1s strong BPSW
798
+ # 3.2s extra strong BPSW
799
+
800
+ # Classic BPSW from page 1401 of the paper. See alternate ideas below.
801
+ return is_strong_bpsw_prp(n)
802
+
803
+ # Using extra strong test, which is somewhat faster
804
+ #return mr(n, [2]) and is_extra_strong_lucas_prp(n)
805
+
806
+ # Add a random M-R base
807
+ #import random
808
+ #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
809
+
810
+
811
+ def is_gaussian_prime(num):
812
+ r"""Test if num is a Gaussian prime number.
813
+
814
+ References
815
+ ==========
816
+
817
+ .. [1] https://oeis.org/wiki/Gaussian_primes
818
+ """
819
+
820
+ num = sympify(num)
821
+ a, b = num.as_real_imag()
822
+ a = as_int(a, strict=False)
823
+ b = as_int(b, strict=False)
824
+ if a == 0:
825
+ b = abs(b)
826
+ return isprime(b) and b % 4 == 3
827
+ elif b == 0:
828
+ a = abs(a)
829
+ return isprime(a) and a % 4 == 3
830
+ return isprime(a**2 + b**2)
.venv/Lib/site-packages/sympy/ntheory/qs.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import exp, log
2
+ from sympy.core.random import _randint
3
+ from sympy.external.gmpy import bit_scan1, gcd, invert, sqrt as isqrt
4
+ from sympy.ntheory.factor_ import _perfect_power
5
+ from sympy.ntheory.primetest import isprime
6
+ from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
7
+
8
+
9
+ class SievePolynomial:
10
+ def __init__(self, a, b, N):
11
+ """This class denotes the sieve polynomial.
12
+ Provide methods to compute `(a*x + b)**2 - N` and
13
+ `a*x + b` when given `x`.
14
+
15
+ Parameters
16
+ ==========
17
+
18
+ a : parameter of the sieve polynomial
19
+ b : parameter of the sieve polynomial
20
+ N : number to be factored
21
+
22
+ """
23
+ self.a = a
24
+ self.b = b
25
+ self.a2 = a**2
26
+ self.ab = 2*a*b
27
+ self.b2 = b**2 - N
28
+
29
+ def eval_u(self, x):
30
+ return self.a*x + self.b
31
+
32
+ def eval_v(self, x):
33
+ return (self.a2*x + self.ab)*x + self.b2
34
+
35
+
36
+ class FactorBaseElem:
37
+ """This class stores an element of the `factor_base`.
38
+ """
39
+ def __init__(self, prime, tmem_p, log_p):
40
+ """
41
+ Initialization of factor_base_elem.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ prime : prime number of the factor_base
47
+ tmem_p : Integer square root of x**2 = n mod prime
48
+ log_p : Compute Natural Logarithm of the prime
49
+ """
50
+ self.prime = prime
51
+ self.tmem_p = tmem_p
52
+ self.log_p = log_p
53
+ # `soln1` and `soln2` are solutions to
54
+ # the equation `(a*x + b)**2 - N = 0 (mod p)`.
55
+ self.soln1 = None
56
+ self.soln2 = None
57
+ self.b_ainv = None
58
+
59
+
60
+ def _generate_factor_base(prime_bound, n):
61
+ """Generate `factor_base` for Quadratic Sieve. The `factor_base`
62
+ consists of all the points whose ``legendre_symbol(n, p) == 1``
63
+ and ``p < num_primes``. Along with the prime `factor_base` also stores
64
+ natural logarithm of prime and the residue n modulo p.
65
+ It also returns the of primes numbers in the `factor_base` which are
66
+ close to 1000 and 5000.
67
+
68
+ Parameters
69
+ ==========
70
+
71
+ prime_bound : upper prime bound of the factor_base
72
+ n : integer to be factored
73
+ """
74
+ from sympy.ntheory.generate import sieve
75
+ factor_base = []
76
+ idx_1000, idx_5000 = None, None
77
+ for prime in sieve.primerange(1, prime_bound):
78
+ if pow(n, (prime - 1) // 2, prime) == 1:
79
+ if prime > 1000 and idx_1000 is None:
80
+ idx_1000 = len(factor_base) - 1
81
+ if prime > 5000 and idx_5000 is None:
82
+ idx_5000 = len(factor_base) - 1
83
+ residue = _sqrt_mod_prime_power(n, prime, 1)[0]
84
+ log_p = round(log(prime)*2**10)
85
+ factor_base.append(FactorBaseElem(prime, residue, log_p))
86
+ return idx_1000, idx_5000, factor_base
87
+
88
+
89
+ def _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
90
+ """ Generate sieve polynomials indefinitely.
91
+ Information such as `soln1` in the `factor_base` associated with
92
+ the polynomial is modified in place.
93
+
94
+ Parameters
95
+ ==========
96
+
97
+ N : Number to be factored
98
+ M : sieve interval
99
+ factor_base : factor_base primes
100
+ idx_1000 : index of prime number in the factor_base near 1000
101
+ idx_5000 : index of prime number in the factor_base near to 5000
102
+ randint : A callable that takes two integers (a, b) and returns a random integer
103
+ n such that a <= n <= b, similar to `random.randint`.
104
+ """
105
+ approx_val = log(2*N)/2 - log(M)
106
+ start = idx_1000 or 0
107
+ end = idx_5000 or (len(factor_base) - 1)
108
+ while True:
109
+ # Choose `a` that is close to `sqrt(2*N) / M`
110
+ best_a, best_q, best_ratio = None, None, None
111
+ for _ in range(50):
112
+ a = 1
113
+ q = []
114
+ while log(a) < approx_val:
115
+ rand_p = 0
116
+ while(rand_p == 0 or rand_p in q):
117
+ rand_p = randint(start, end)
118
+ p = factor_base[rand_p].prime
119
+ a *= p
120
+ q.append(rand_p)
121
+ ratio = exp(log(a) - approx_val)
122
+ if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
123
+ best_q = q
124
+ best_a = a
125
+ best_ratio = ratio
126
+
127
+ # Set `b` using the Chinese remainder theorem
128
+ a = best_a
129
+ q = best_q
130
+ B = []
131
+ for val in q:
132
+ q_l = factor_base[val].prime
133
+ gamma = factor_base[val].tmem_p * invert(a // q_l, q_l) % q_l
134
+ if 2*gamma > q_l:
135
+ gamma = q_l - gamma
136
+ B.append(a//q_l*gamma)
137
+ b = sum(B)
138
+ g = SievePolynomial(a, b, N)
139
+ for fb in factor_base:
140
+ if a % fb.prime == 0:
141
+ fb.soln1 = None
142
+ continue
143
+ a_inv = invert(a, fb.prime)
144
+ fb.b_ainv = [2*b_elem*a_inv % fb.prime for b_elem in B]
145
+ fb.soln1 = (a_inv*(fb.tmem_p - b)) % fb.prime
146
+ fb.soln2 = (a_inv*(-fb.tmem_p - b)) % fb.prime
147
+ yield g
148
+
149
+ # Update `b` with Gray code
150
+ for i in range(1, 2**(len(B)-1)):
151
+ v = bit_scan1(i)
152
+ neg_pow = 2*((i >> (v + 1)) % 2) - 1
153
+ b = g.b + 2*neg_pow*B[v]
154
+ a = g.a
155
+ g = SievePolynomial(a, b, N)
156
+ for fb in factor_base:
157
+ if fb.soln1 is None:
158
+ continue
159
+ fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v]) % fb.prime
160
+ fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v]) % fb.prime
161
+ yield g
162
+
163
+
164
+ def _gen_sieve_array(M, factor_base):
165
+ """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
166
+ that does not divide the coefficient `a` we add log_p over the sieve_array
167
+ such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i`
168
+ is an integer. When p = 2 then log_p is only added using
169
+ ``-M <= soln1 + i*p <= M``.
170
+
171
+ Parameters
172
+ ==========
173
+
174
+ M : sieve interval
175
+ factor_base : factor_base primes
176
+ """
177
+ sieve_array = [0]*(2*M + 1)
178
+ for factor in factor_base:
179
+ if factor.soln1 is None: #The prime does not divides a
180
+ continue
181
+ for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
182
+ sieve_array[idx] += factor.log_p
183
+ if factor.prime == 2:
184
+ continue
185
+ #if prime is 2 then sieve only with soln_1_p
186
+ for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
187
+ sieve_array[idx] += factor.log_p
188
+ return sieve_array
189
+
190
+
191
+ def _check_smoothness(num, factor_base):
192
+ r""" Check if `num` is smooth with respect to the given `factor_base`
193
+ and compute its factorization vector.
194
+
195
+ Parameters
196
+ ==========
197
+
198
+ num : integer whose smootheness is to be checked
199
+ factor_base : factor_base primes
200
+ """
201
+ if num < 0:
202
+ num *= -1
203
+ vec = 1
204
+ else:
205
+ vec = 0
206
+ for i, fb in enumerate(factor_base, 1):
207
+ if num % fb.prime:
208
+ continue
209
+ e = 1
210
+ num //= fb.prime
211
+ while num % fb.prime == 0:
212
+ e += 1
213
+ num //= fb.prime
214
+ if e % 2:
215
+ vec += 1 << i
216
+ return vec, num
217
+
218
+
219
+ def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
220
+ """Trial division stage. Here we trial divide the values generetated
221
+ by sieve_poly in the sieve interval and if it is a smooth number then
222
+ it is stored in `smooth_relations`. Moreover, if we find two partial relations
223
+ with same large prime then they are combined to form a smooth relation.
224
+ First we iterate over sieve array and look for values which are greater
225
+ than accumulated_val, as these values have a high chance of being smooth
226
+ number. Then using these values we find smooth relations.
227
+ In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
228
+ with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
229
+ to form a smooth relation.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ N : Number to be factored
235
+ M : sieve interval
236
+ factor_base : factor_base primes
237
+ sieve_array : stores log_p values
238
+ sieve_poly : polynomial from which we find smooth relations
239
+ partial_relations : stores partial relations with one large prime
240
+ ERROR_TERM : error term for accumulated_val
241
+ """
242
+ accumulated_val = (log(M) + log(N)/2 - ERROR_TERM) * 2**10
243
+ smooth_relations = []
244
+ proper_factor = set()
245
+ partial_relation_upper_bound = 128*factor_base[-1].prime
246
+ for x, val in enumerate(sieve_array, -M):
247
+ if val < accumulated_val:
248
+ continue
249
+ v = sieve_poly.eval_v(x)
250
+ vec, num = _check_smoothness(v, factor_base)
251
+ if num == 1:
252
+ smooth_relations.append((sieve_poly.eval_u(x), v, vec))
253
+ elif num < partial_relation_upper_bound and isprime(num):
254
+ if N % num == 0:
255
+ proper_factor.add(num)
256
+ continue
257
+ u = sieve_poly.eval_u(x)
258
+ if num in partial_relations:
259
+ u_prev, v_prev, vec_prev = partial_relations.pop(num)
260
+ u = u*u_prev*invert(num, N) % N
261
+ v = v*v_prev // num**2
262
+ vec ^= vec_prev
263
+ smooth_relations.append((u, v, vec))
264
+ else:
265
+ partial_relations[num] = (u, v, vec)
266
+ return smooth_relations, proper_factor
267
+
268
+
269
+ def _find_factor(N, smooth_relations, col):
270
+ """ Finds proper factor of N using fast gaussian reduction for modulo 2 matrix.
271
+
272
+ Parameters
273
+ ==========
274
+
275
+ N : Number to be factored
276
+ smooth_relations : Smooth relations vectors matrix
277
+ col : Number of columns in the matrix
278
+
279
+ Reference
280
+ ==========
281
+
282
+ .. [1] A fast algorithm for gaussian elimination over GF(2) and
283
+ its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige
284
+ """
285
+ matrix = [s_relation[2] for s_relation in smooth_relations]
286
+ row = len(matrix)
287
+ mark = [False] * row
288
+ for pos in range(col):
289
+ m = 1 << pos
290
+ for i in range(row):
291
+ if p := matrix[i] & m:
292
+ add_col = p ^ matrix[i]
293
+ matrix[i] = m
294
+ mark[i] = True
295
+ for j in range(i + 1, row):
296
+ if matrix[j] & m:
297
+ matrix[j] ^= add_col
298
+ break
299
+
300
+ for m, mat, rel in zip(mark, matrix, smooth_relations):
301
+ if m:
302
+ continue
303
+ u, v = rel[0], rel[1]
304
+ for m1, mat1, rel1 in zip(mark, matrix, smooth_relations):
305
+ if m1 and mat & mat1:
306
+ u *= rel1[0]
307
+ v *= rel1[1]
308
+ # assert is_square(v)
309
+ v = isqrt(v)
310
+ if 1 < (g := gcd(u - v, N)) < N:
311
+ yield g
312
+
313
+
314
+ def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
315
+ """Performs factorization using Self-Initializing Quadratic Sieve.
316
+ In SIQS, let N be a number to be factored, and this N should not be a
317
+ perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
318
+ ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
319
+ In order to find these integers X and Y we try to find relations of form
320
+ t**2 = u modN where u is a product of small primes. If we have enough of
321
+ these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
322
+ the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
323
+
324
+ Here, several optimizations are done like using multiple polynomials for
325
+ sieving, fast changing between polynomials and using partial relations.
326
+ The use of partial relations can speeds up the factoring by 2 times.
327
+
328
+ Parameters
329
+ ==========
330
+
331
+ N : Number to be Factored
332
+ prime_bound : upper bound for primes in the factor base
333
+ M : Sieve Interval
334
+ ERROR_TERM : Error term for checking smoothness
335
+ seed : seed of random number generator
336
+
337
+ Returns
338
+ =======
339
+
340
+ set(int) : A set of factors of N without considering multiplicity.
341
+ Returns ``{N}`` if factorization fails.
342
+
343
+ Examples
344
+ ========
345
+
346
+ >>> from sympy.ntheory import qs
347
+ >>> qs(25645121643901801, 2000, 10000)
348
+ {5394769, 4753701529}
349
+ >>> qs(9804659461513846513, 2000, 10000)
350
+ {4641991, 2112166839943}
351
+
352
+ See Also
353
+ ========
354
+
355
+ qs_factor
356
+
357
+ References
358
+ ==========
359
+
360
+ .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
361
+ .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
362
+ """
363
+ return set(qs_factor(N, prime_bound, M, ERROR_TERM, seed))
364
+
365
+
366
+ def qs_factor(N, prime_bound, M, ERROR_TERM=25, seed=1234):
367
+ """ Performs factorization using Self-Initializing Quadratic Sieve.
368
+
369
+ Parameters
370
+ ==========
371
+
372
+ N : Number to be Factored
373
+ prime_bound : upper bound for primes in the factor base
374
+ M : Sieve Interval
375
+ ERROR_TERM : Error term for checking smoothness
376
+ seed : seed of random number generator
377
+
378
+ Returns
379
+ =======
380
+
381
+ dict[int, int] : Factors of N.
382
+ Returns ``{N: 1}`` if factorization fails.
383
+ Note that the key is not always a prime number.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy.ntheory import qs_factor
389
+ >>> qs_factor(1009 * 100003, 2000, 10000)
390
+ {1009: 1, 100003: 1}
391
+
392
+ See Also
393
+ ========
394
+
395
+ qs
396
+
397
+ """
398
+ if N < 2:
399
+ raise ValueError("N should be greater than 1")
400
+ factors = {}
401
+ smooth_relations = []
402
+ partial_relations = {}
403
+ # Eliminate the possibility of even numbers,
404
+ # prime numbers, and perfect powers.
405
+ if N % 2 == 0:
406
+ e = 1
407
+ N //= 2
408
+ while N % 2 == 0:
409
+ N //= 2
410
+ e += 1
411
+ factors[2] = e
412
+ if isprime(N):
413
+ factors[N] = 1
414
+ return factors
415
+ if result := _perfect_power(N, 3):
416
+ n, e = result
417
+ factors[n] = e
418
+ return factors
419
+ N_copy = N
420
+ randint = _randint(seed)
421
+ idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
422
+ threshold = len(factor_base) * 105//100
423
+ for g in _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
424
+ sieve_array = _gen_sieve_array(M, factor_base)
425
+ s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, g, partial_relations, ERROR_TERM)
426
+ smooth_relations += s_rel
427
+ for p in p_f:
428
+ if N_copy % p:
429
+ continue
430
+ e = 1
431
+ N_copy //= p
432
+ while N_copy % p == 0:
433
+ N_copy //= p
434
+ e += 1
435
+ factors[p] = e
436
+ if threshold <= len(smooth_relations):
437
+ break
438
+
439
+ for factor in _find_factor(N, smooth_relations, len(factor_base) + 1):
440
+ if N_copy % factor == 0:
441
+ e = 1
442
+ N_copy //= factor
443
+ while N_copy % factor == 0:
444
+ N_copy //= factor
445
+ e += 1
446
+ factors[factor] = e
447
+ if N_copy == 1 or isprime(N_copy):
448
+ break
449
+ if N_copy != 1:
450
+ factors[N_copy] = 1
451
+ return factors
.venv/Lib/site-packages/sympy/ntheory/residue_ntheory.py ADDED
@@ -0,0 +1,1963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.external.gmpy import (gcd, lcm, invert, sqrt, jacobi,
4
+ bit_scan1, remove)
5
+ from sympy.polys import Poly
6
+ from sympy.polys.domains import ZZ
7
+ from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence, gf_csolve
8
+ from .primetest import isprime
9
+ from .generate import primerange
10
+ from .factor_ import factorint, _perfect_power
11
+ from .modular import crt
12
+ from sympy.utilities.decorator import deprecated
13
+ from sympy.utilities.memoization import recurrence_memo
14
+ from sympy.utilities.misc import as_int
15
+ from sympy.utilities.iterables import iproduct
16
+ from sympy.core.random import _randint, randint
17
+
18
+ from itertools import product
19
+
20
+
21
+ def n_order(a, n):
22
+ r""" Returns the order of ``a`` modulo ``n``.
23
+
24
+ Explanation
25
+ ===========
26
+
27
+ The order of ``a`` modulo ``n`` is the smallest integer
28
+ ``k`` such that `a^k` leaves a remainder of 1 with ``n``.
29
+
30
+ Parameters
31
+ ==========
32
+
33
+ a : integer
34
+ n : integer, n > 1. a and n should be relatively prime
35
+
36
+ Returns
37
+ =======
38
+
39
+ int : the order of ``a`` modulo ``n``
40
+
41
+ Raises
42
+ ======
43
+
44
+ ValueError
45
+ If `n \le 1` or `\gcd(a, n) \neq 1`.
46
+ If ``a`` or ``n`` is not an integer.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.ntheory import n_order
52
+ >>> n_order(3, 7)
53
+ 6
54
+ >>> n_order(4, 7)
55
+ 3
56
+
57
+ See Also
58
+ ========
59
+
60
+ is_primitive_root
61
+ We say that ``a`` is a primitive root of ``n``
62
+ when the order of ``a`` modulo ``n`` equals ``totient(n)``
63
+
64
+ """
65
+ a, n = as_int(a), as_int(n)
66
+ if n <= 1:
67
+ raise ValueError("n should be an integer greater than 1")
68
+ a = a % n
69
+ # Trivial
70
+ if a == 1:
71
+ return 1
72
+ if gcd(a, n) != 1:
73
+ raise ValueError("The two numbers should be relatively prime")
74
+ a_order = 1
75
+ for p, e in factorint(n).items():
76
+ pe = p**e
77
+ pe_order = (p - 1) * p**(e - 1)
78
+ factors = factorint(p - 1)
79
+ if e > 1:
80
+ factors[p] = e - 1
81
+ order = 1
82
+ for px, ex in factors.items():
83
+ x = pow(a, pe_order // px**ex, pe)
84
+ while x != 1:
85
+ x = pow(x, px, pe)
86
+ order *= px
87
+ a_order = lcm(a_order, order)
88
+ return int(a_order)
89
+
90
+
91
+ def _primitive_root_prime_iter(p):
92
+ r""" Generates the primitive roots for a prime ``p``.
93
+
94
+ Explanation
95
+ ===========
96
+
97
+ The primitive roots generated are not necessarily sorted.
98
+ However, the first one is the smallest primitive root.
99
+
100
+ Find the element whose order is ``p-1`` from the smaller one.
101
+ If we can find the first primitive root ``g``, we can use the following theorem.
102
+
103
+ .. math ::
104
+ \operatorname{ord}(g^k) = \frac{\operatorname{ord}(g)}{\gcd(\operatorname{ord}(g), k)}
105
+
106
+ From the assumption that `\operatorname{ord}(g)=p-1`,
107
+ it is a necessary and sufficient condition for
108
+ `\operatorname{ord}(g^k)=p-1` that `\gcd(p-1, k)=1`.
109
+
110
+ Parameters
111
+ ==========
112
+
113
+ p : odd prime
114
+
115
+ Yields
116
+ ======
117
+
118
+ int
119
+ the primitive roots of ``p``
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
125
+ >>> sorted(_primitive_root_prime_iter(19))
126
+ [2, 3, 10, 13, 14, 15]
127
+
128
+ References
129
+ ==========
130
+
131
+ .. [1] W. Stein "Elementary Number Theory" (2011), page 44
132
+
133
+ """
134
+ if p == 3:
135
+ yield 2
136
+ return
137
+ # Let p = +-1 (mod 4a). Legendre symbol (a/p) = 1, so `a` is not the primitive root.
138
+ # Corollary : If p = +-1 (mod 8), then 2 is not the primitive root of p.
139
+ g_min = 3 if p % 8 in [1, 7] else 2
140
+ if p < 41:
141
+ # small case
142
+ g = 5 if p == 23 else g_min
143
+ else:
144
+ v = [(p - 1) // i for i in factorint(p - 1).keys()]
145
+ for g in range(g_min, p):
146
+ if all(pow(g, pw, p) != 1 for pw in v):
147
+ break
148
+ yield g
149
+ # g**k is the primitive root of p iff gcd(p - 1, k) = 1
150
+ for k in range(3, p, 2):
151
+ if gcd(p - 1, k) == 1:
152
+ yield pow(g, k, p)
153
+
154
+
155
+ def _primitive_root_prime_power_iter(p, e):
156
+ r""" Generates the primitive roots of `p^e`.
157
+
158
+ Explanation
159
+ ===========
160
+
161
+ Let ``g`` be the primitive root of ``p``.
162
+ If `g^{p-1} \not\equiv 1 \pmod{p^2}`, then ``g`` is primitive root of `p^e`.
163
+ Thus, if we find a primitive root ``g`` of ``p``,
164
+ then `g, g+p, g+2p, \ldots, g+(p-1)p` are primitive roots of `p^2` except one.
165
+ That one satisfies `\hat{g}^{p-1} \equiv 1 \pmod{p^2}`.
166
+ If ``h`` is the primitive root of `p^2`,
167
+ then `h, h+p^2, h+2p^2, \ldots, h+(p^{e-2}-1)p^e` are primitive roots of `p^e`.
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ p : odd prime
173
+ e : positive integer
174
+
175
+ Yields
176
+ ======
177
+
178
+ int
179
+ the primitive roots of `p^e`
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power_iter
185
+ >>> sorted(_primitive_root_prime_power_iter(5, 2))
186
+ [2, 3, 8, 12, 13, 17, 22, 23]
187
+
188
+ """
189
+ if e == 1:
190
+ yield from _primitive_root_prime_iter(p)
191
+ else:
192
+ p2 = p**2
193
+ for g in _primitive_root_prime_iter(p):
194
+ t = (g - pow(g, 2 - p, p2)) % p2
195
+ for k in range(0, p2, p):
196
+ if k != t:
197
+ yield from (g + k + m for m in range(0, p**e, p2))
198
+
199
+
200
+ def _primitive_root_prime_power2_iter(p, e):
201
+ r""" Generates the primitive roots of `2p^e`.
202
+
203
+ Explanation
204
+ ===========
205
+
206
+ If ``g`` is the primitive root of ``p**e``,
207
+ then the odd one of ``g`` and ``g+p**e`` is the primitive root of ``2*p**e``.
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ p : odd prime
213
+ e : positive integer
214
+
215
+ Yields
216
+ ======
217
+
218
+ int
219
+ the primitive roots of `2p^e`
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power2_iter
225
+ >>> sorted(_primitive_root_prime_power2_iter(5, 2))
226
+ [3, 13, 17, 23, 27, 33, 37, 47]
227
+
228
+ """
229
+ for g in _primitive_root_prime_power_iter(p, e):
230
+ if g % 2 == 1:
231
+ yield g
232
+ else:
233
+ yield g + p**e
234
+
235
+
236
+ def primitive_root(p, smallest=True):
237
+ r""" Returns a primitive root of ``p`` or None.
238
+
239
+ Explanation
240
+ ===========
241
+
242
+ For the definition of primitive root,
243
+ see the explanation of ``is_primitive_root``.
244
+
245
+ The primitive root of ``p`` exist only for
246
+ `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
247
+ Now, if we know the primitive root of ``q``,
248
+ we can calculate the primitive root of `q^e`,
249
+ and if we know the primitive root of `q^e`,
250
+ we can calculate the primitive root of `2q^e`.
251
+ When there is no need to find the smallest primitive root,
252
+ this property can be used to obtain a fast primitive root.
253
+ On the other hand, when we want the smallest primitive root,
254
+ we naively determine whether it is a primitive root or not.
255
+
256
+ Parameters
257
+ ==========
258
+
259
+ p : integer, p > 1
260
+ smallest : if True the smallest primitive root is returned or None
261
+
262
+ Returns
263
+ =======
264
+
265
+ int | None :
266
+ If the primitive root exists, return the primitive root of ``p``.
267
+ If not, return None.
268
+
269
+ Raises
270
+ ======
271
+
272
+ ValueError
273
+ If `p \le 1` or ``p`` is not an integer.
274
+
275
+ Examples
276
+ ========
277
+
278
+ >>> from sympy.ntheory.residue_ntheory import primitive_root
279
+ >>> primitive_root(19)
280
+ 2
281
+ >>> primitive_root(21) is None
282
+ True
283
+ >>> primitive_root(50, smallest=False)
284
+ 27
285
+
286
+ See Also
287
+ ========
288
+
289
+ is_primitive_root
290
+
291
+ References
292
+ ==========
293
+
294
+ .. [1] W. Stein "Elementary Number Theory" (2011), page 44
295
+ .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
296
+
297
+ """
298
+ p = as_int(p)
299
+ if p <= 1:
300
+ raise ValueError("p should be an integer greater than 1")
301
+ if p <= 4:
302
+ return p - 1
303
+ p_even = p % 2 == 0
304
+ if not p_even:
305
+ q = p # p is odd
306
+ elif p % 4:
307
+ q = p//2 # p had 1 factor of 2
308
+ else:
309
+ return None # p had more than one factor of 2
310
+ if isprime(q):
311
+ e = 1
312
+ else:
313
+ m = _perfect_power(q, 3)
314
+ if not m:
315
+ return None
316
+ q, e = m
317
+ if not isprime(q):
318
+ return None
319
+ if not smallest:
320
+ if p_even:
321
+ return next(_primitive_root_prime_power2_iter(q, e))
322
+ return next(_primitive_root_prime_power_iter(q, e))
323
+ if p_even:
324
+ for i in range(3, p, 2):
325
+ if i % q and is_primitive_root(i, p):
326
+ return i
327
+ g = next(_primitive_root_prime_iter(q))
328
+ if e == 1 or pow(g, q - 1, q**2) != 1:
329
+ return g
330
+ for i in range(g + 1, p):
331
+ if i % q and is_primitive_root(i, p):
332
+ return i
333
+
334
+
335
+ def is_primitive_root(a, p):
336
+ r""" Returns True if ``a`` is a primitive root of ``p``.
337
+
338
+ Explanation
339
+ ===========
340
+
341
+ ``a`` is said to be the primitive root of ``p`` if `\gcd(a, p) = 1` and
342
+ `\phi(p)` is the smallest positive number s.t.
343
+
344
+ `a^{\phi(p)} \equiv 1 \pmod{p}`.
345
+
346
+ where `\phi(p)` is Euler's totient function.
347
+
348
+ The primitive root of ``p`` exist only for
349
+ `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
350
+ Hence, if it is not such a ``p``, it returns False.
351
+ To determine the primitive root, we need to know
352
+ the prime factorization of ``q-1``.
353
+ The hardness of the determination depends on this complexity.
354
+
355
+ Parameters
356
+ ==========
357
+
358
+ a : integer
359
+ p : integer, ``p`` > 1. ``a`` and ``p`` should be relatively prime
360
+
361
+ Returns
362
+ =======
363
+
364
+ bool : If True, ``a`` is the primitive root of ``p``.
365
+
366
+ Raises
367
+ ======
368
+
369
+ ValueError
370
+ If `p \le 1` or `\gcd(a, p) \neq 1`.
371
+ If ``a`` or ``p`` is not an integer.
372
+
373
+ Examples
374
+ ========
375
+
376
+ >>> from sympy.functions.combinatorial.numbers import totient
377
+ >>> from sympy.ntheory import is_primitive_root, n_order
378
+ >>> is_primitive_root(3, 10)
379
+ True
380
+ >>> is_primitive_root(9, 10)
381
+ False
382
+ >>> n_order(3, 10) == totient(10)
383
+ True
384
+ >>> n_order(9, 10) == totient(10)
385
+ False
386
+
387
+ See Also
388
+ ========
389
+
390
+ primitive_root
391
+
392
+ """
393
+ a, p = as_int(a), as_int(p)
394
+ if p <= 1:
395
+ raise ValueError("p should be an integer greater than 1")
396
+ a = a % p
397
+ if gcd(a, p) != 1:
398
+ raise ValueError("The two numbers should be relatively prime")
399
+ # Primitive root of p exist only for
400
+ # p = 2, 4, q**e, 2*q**e (q is odd prime)
401
+ if p <= 4:
402
+ # The primitive root is only p-1.
403
+ return a == p - 1
404
+ if p % 2:
405
+ q = p # p is odd
406
+ elif p % 4:
407
+ q = p//2 # p had 1 factor of 2
408
+ else:
409
+ return False # p had more than one factor of 2
410
+ if isprime(q):
411
+ group_order = q - 1
412
+ factors = factorint(q - 1).keys()
413
+ else:
414
+ m = _perfect_power(q, 3)
415
+ if not m:
416
+ return False
417
+ q, e = m
418
+ if not isprime(q):
419
+ return False
420
+ group_order = q**(e - 1)*(q - 1)
421
+ factors = set(factorint(q - 1).keys())
422
+ factors.add(q)
423
+ return all(pow(a, group_order // prime, p) != 1 for prime in factors)
424
+
425
+
426
+ def _sqrt_mod_tonelli_shanks(a, p):
427
+ """
428
+ Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
429
+
430
+ Assume that the root exists.
431
+
432
+ Parameters
433
+ ==========
434
+
435
+ a : int
436
+ p : int
437
+ prime number. should be ``p % 8 == 1``
438
+
439
+ Returns
440
+ =======
441
+
442
+ int : Generally, there are two roots, but only one is returned.
443
+ Which one is returned is random.
444
+
445
+ Examples
446
+ ========
447
+
448
+ >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_tonelli_shanks
449
+ >>> _sqrt_mod_tonelli_shanks(2, 17) in [6, 11]
450
+ True
451
+
452
+ References
453
+ ==========
454
+
455
+ .. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
456
+ 2nd Edition (2005), page 101, ISBN:978-0387252827
457
+
458
+ """
459
+ s = bit_scan1(p - 1)
460
+ t = p >> s
461
+ # find a non-quadratic residue
462
+ if p % 12 == 5:
463
+ # Legendre symbol (3/p) == -1 if p % 12 in [5, 7]
464
+ d = 3
465
+ elif p % 5 in [2, 3]:
466
+ # Legendre symbol (5/p) == -1 if p % 5 in [2, 3]
467
+ d = 5
468
+ else:
469
+ while 1:
470
+ d = randint(6, p - 1)
471
+ if jacobi(d, p) == -1:
472
+ break
473
+ #assert legendre_symbol(d, p) == -1
474
+ A = pow(a, t, p)
475
+ D = pow(d, t, p)
476
+ m = 0
477
+ for i in range(s):
478
+ adm = A*pow(D, m, p) % p
479
+ adm = pow(adm, 2**(s - 1 - i), p)
480
+ if adm % p == p - 1:
481
+ m += 2**i
482
+ #assert A*pow(D, m, p) % p == 1
483
+ x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
484
+ return x
485
+
486
+
487
+ def sqrt_mod(a, p, all_roots=False):
488
+ """
489
+ Find a root of ``x**2 = a mod p``.
490
+
491
+ Parameters
492
+ ==========
493
+
494
+ a : integer
495
+ p : positive integer
496
+ all_roots : if True the list of roots is returned or None
497
+
498
+ Notes
499
+ =====
500
+
501
+ If there is no root it is returned None; else the returned root
502
+ is less or equal to ``p // 2``; in general is not the smallest one.
503
+ It is returned ``p // 2`` only if it is the only root.
504
+
505
+ Use ``all_roots`` only when it is expected that all the roots fit
506
+ in memory; otherwise use ``sqrt_mod_iter``.
507
+
508
+ Examples
509
+ ========
510
+
511
+ >>> from sympy.ntheory import sqrt_mod
512
+ >>> sqrt_mod(11, 43)
513
+ 21
514
+ >>> sqrt_mod(17, 32, True)
515
+ [7, 9, 23, 25]
516
+ """
517
+ if all_roots:
518
+ return sorted(sqrt_mod_iter(a, p))
519
+ p = abs(as_int(p))
520
+ halfp = p // 2
521
+ x = None
522
+ for r in sqrt_mod_iter(a, p):
523
+ if r < halfp:
524
+ return r
525
+ elif r > halfp:
526
+ return p - r
527
+ else:
528
+ x = r
529
+ return x
530
+
531
+
532
+ def sqrt_mod_iter(a, p, domain=int):
533
+ """
534
+ Iterate over solutions to ``x**2 = a mod p``.
535
+
536
+ Parameters
537
+ ==========
538
+
539
+ a : integer
540
+ p : positive integer
541
+ domain : integer domain, ``int``, ``ZZ`` or ``Integer``
542
+
543
+ Examples
544
+ ========
545
+
546
+ >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
547
+ >>> list(sqrt_mod_iter(11, 43))
548
+ [21, 22]
549
+
550
+ See Also
551
+ ========
552
+
553
+ sqrt_mod : Same functionality, but you want a sorted list or only one solution.
554
+
555
+ """
556
+ a, p = as_int(a), abs(as_int(p))
557
+ v = []
558
+ pv = []
559
+ _product = product
560
+ for px, ex in factorint(p).items():
561
+ if a % px:
562
+ # `len(rx)` is at most 4
563
+ rx = _sqrt_mod_prime_power(a, px, ex)
564
+ else:
565
+ # `len(list(rx))` can be assumed to be large.
566
+ # The `itertools.product` is disadvantageous in terms of memory usage.
567
+ # It is also inferior to iproduct in speed if not all Cartesian products are needed.
568
+ rx = _sqrt_mod1(a, px, ex)
569
+ _product = iproduct
570
+ if not rx:
571
+ return
572
+ v.append(rx)
573
+ pv.append(px**ex)
574
+ if len(v) == 1:
575
+ yield from map(domain, v[0])
576
+ else:
577
+ mm, e, s = gf_crt1(pv, ZZ)
578
+ for vx in _product(*v):
579
+ yield domain(gf_crt2(vx, pv, mm, e, s, ZZ))
580
+
581
+
582
+ def _sqrt_mod_prime_power(a, p, k):
583
+ """
584
+ Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``.
585
+ If no solution exists, return ``None``.
586
+ Solutions are returned in an ascending list.
587
+
588
+ Parameters
589
+ ==========
590
+
591
+ a : integer
592
+ p : prime number
593
+ k : positive integer
594
+
595
+ Examples
596
+ ========
597
+
598
+ >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
599
+ >>> _sqrt_mod_prime_power(11, 43, 1)
600
+ [21, 22]
601
+
602
+ References
603
+ ==========
604
+
605
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 160
606
+ .. [2] http://www.numbertheory.org/php/squareroot.html
607
+ .. [3] [Gathen99]_
608
+ """
609
+ pk = p**k
610
+ a = a % pk
611
+
612
+ if p == 2:
613
+ # see Ref.[2]
614
+ if a % 8 != 1:
615
+ return None
616
+ # Trivial
617
+ if k <= 3:
618
+ return list(range(1, pk, 2))
619
+ r = 1
620
+ # r is one of the solutions to x**2 - a = 0 (mod 2**3).
621
+ # Hensel lift them to solutions of x**2 - a = 0 (mod 2**k)
622
+ # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
623
+ # then r + 2**(nx - 1) is a root mod 2**(nx+1)
624
+ for nx in range(3, k):
625
+ if ((r**2 - a) >> nx) % 2:
626
+ r += 1 << (nx - 1)
627
+ # r is a solution of x**2 - a = 0 (mod 2**k), and
628
+ # there exist other solutions -r, r+h, -(r+h), and these are all solutions.
629
+ h = 1 << (k - 1)
630
+ return sorted([r, pk - r, (r + h) % pk, -(r + h) % pk])
631
+
632
+ # If the Legendre symbol (a/p) is not 1, no solution exists.
633
+ if jacobi(a, p) != 1:
634
+ return None
635
+ if p % 4 == 3:
636
+ res = pow(a, (p + 1) // 4, p)
637
+ elif p % 8 == 5:
638
+ res = pow(a, (p + 3) // 8, p)
639
+ if pow(res, 2, p) != a % p:
640
+ res = res * pow(2, (p - 1) // 4, p) % p
641
+ else:
642
+ res = _sqrt_mod_tonelli_shanks(a, p)
643
+ if k > 1:
644
+ # Hensel lifting with Newton iteration, see Ref.[3] chapter 9
645
+ # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
646
+ px = p
647
+ for _ in range(k.bit_length() - 1):
648
+ px = px**2
649
+ frinv = invert(2*res, px)
650
+ res = (res - (res**2 - a)*frinv) % px
651
+ if k & (k - 1): # If k is not a power of 2
652
+ frinv = invert(2*res, pk)
653
+ res = (res - (res**2 - a)*frinv) % pk
654
+ return sorted([res, pk - res])
655
+
656
+
657
+ def _sqrt_mod1(a, p, n):
658
+ """
659
+ Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``.
660
+ If no solution exists, return ``None``.
661
+
662
+ Parameters
663
+ ==========
664
+
665
+ a : integer
666
+ p : prime number, p must divide a
667
+ n : positive integer
668
+
669
+ References
670
+ ==========
671
+
672
+ .. [1] http://www.numbertheory.org/php/squareroot.html
673
+ """
674
+ pn = p**n
675
+ a = a % pn
676
+ if a == 0:
677
+ # case gcd(a, p**k) = p**n
678
+ return range(0, pn, p**((n + 1) // 2))
679
+ # case gcd(a, p**k) = p**r, r < n
680
+ a, r = remove(a, p)
681
+ if r % 2 == 1:
682
+ return None
683
+ res = _sqrt_mod_prime_power(a, p, n - r)
684
+ if res is None:
685
+ return None
686
+ m = r // 2
687
+ return (x for rx in res for x in range(rx*p**m, pn, p**(n - m)))
688
+
689
+
690
+ def is_quad_residue(a, p):
691
+ """
692
+ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
693
+ i.e a % p in set([i**2 % p for i in range(p)]).
694
+
695
+ Parameters
696
+ ==========
697
+
698
+ a : integer
699
+ p : positive integer
700
+
701
+ Returns
702
+ =======
703
+
704
+ bool : If True, ``x**2 == a (mod p)`` has solution.
705
+
706
+ Raises
707
+ ======
708
+
709
+ ValueError
710
+ If ``a``, ``p`` is not integer.
711
+ If ``p`` is not positive.
712
+
713
+ Examples
714
+ ========
715
+
716
+ >>> from sympy.ntheory import is_quad_residue
717
+ >>> is_quad_residue(21, 100)
718
+ True
719
+
720
+ Indeed, ``pow(39, 2, 100)`` would be 21.
721
+
722
+ >>> is_quad_residue(21, 120)
723
+ False
724
+
725
+ That is, for any integer ``x``, ``pow(x, 2, 120)`` is not 21.
726
+
727
+ If ``p`` is an odd
728
+ prime, an iterative method is used to make the determination:
729
+
730
+ >>> from sympy.ntheory import is_quad_residue
731
+ >>> sorted(set([i**2 % 7 for i in range(7)]))
732
+ [0, 1, 2, 4]
733
+ >>> [j for j in range(7) if is_quad_residue(j, 7)]
734
+ [0, 1, 2, 4]
735
+
736
+ See Also
737
+ ========
738
+
739
+ legendre_symbol, jacobi_symbol, sqrt_mod
740
+ """
741
+ a, p = as_int(a), as_int(p)
742
+ if p < 1:
743
+ raise ValueError('p must be > 0')
744
+ a %= p
745
+ if a < 2 or p < 3:
746
+ return True
747
+ # Since we want to compute the Jacobi symbol,
748
+ # we separate p into the odd part and the rest.
749
+ t = bit_scan1(p)
750
+ if t:
751
+ # The existence of a solution to a power of 2 is determined
752
+ # using the logic of `p==2` in `_sqrt_mod_prime_power` and `_sqrt_mod1`.
753
+ a_ = a % (1 << t)
754
+ if a_:
755
+ r = bit_scan1(a_)
756
+ if r % 2 or (a_ >> r) & 6:
757
+ return False
758
+ p >>= t
759
+ a %= p
760
+ if a < 2 or p < 3:
761
+ return True
762
+ # If Jacobi symbol is -1 or p is prime, can be determined by Jacobi symbol only
763
+ j = jacobi(a, p)
764
+ if j == -1 or isprime(p):
765
+ return j == 1
766
+ # Checks if `x**2 = a (mod p)` has a solution
767
+ for px, ex in factorint(p).items():
768
+ if a % px:
769
+ if jacobi(a, px) != 1:
770
+ return False
771
+ else:
772
+ a_ = a % px**ex
773
+ if a_ == 0:
774
+ continue
775
+ a_, r = remove(a_, px)
776
+ if r % 2 or jacobi(a_, px) != 1:
777
+ return False
778
+ return True
779
+
780
+
781
+ def is_nthpow_residue(a, n, m):
782
+ """
783
+ Returns True if ``x**n == a (mod m)`` has solutions.
784
+
785
+ References
786
+ ==========
787
+
788
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
789
+
790
+ """
791
+ a = a % m
792
+ a, n, m = as_int(a), as_int(n), as_int(m)
793
+ if m <= 0:
794
+ raise ValueError('m must be > 0')
795
+ if n < 0:
796
+ raise ValueError('n must be >= 0')
797
+ if n == 0:
798
+ if m == 1:
799
+ return False
800
+ return a == 1
801
+ if a == 0:
802
+ return True
803
+ if n == 1:
804
+ return True
805
+ if n == 2:
806
+ return is_quad_residue(a, m)
807
+ return all(_is_nthpow_residue_bign_prime_power(a, n, p, e)
808
+ for p, e in factorint(m).items())
809
+
810
+
811
+ def _is_nthpow_residue_bign_prime_power(a, n, p, k):
812
+ r"""
813
+ Returns True if `x^n = a \pmod{p^k}` has solutions for `n > 2`.
814
+
815
+ Parameters
816
+ ==========
817
+
818
+ a : positive integer
819
+ n : integer, n > 2
820
+ p : prime number
821
+ k : positive integer
822
+
823
+ """
824
+ while a % p == 0:
825
+ a %= pow(p, k)
826
+ if not a:
827
+ return True
828
+ a, mu = remove(a, p)
829
+ if mu % n:
830
+ return False
831
+ k -= mu
832
+ if p != 2:
833
+ f = p**(k - 1)*(p - 1) # f = totient(p**k)
834
+ return pow(a, f // gcd(f, n), pow(p, k)) == 1
835
+ if n & 1:
836
+ return True
837
+ c = min(bit_scan1(n) + 2, k)
838
+ return a % pow(2, c) == 1
839
+
840
+
841
+ def _nthroot_mod1(s, q, p, all_roots):
842
+ """
843
+ Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``.
844
+ Assume that the root exists.
845
+
846
+ Parameters
847
+ ==========
848
+
849
+ s : integer
850
+ q : integer, n > 2. ``q`` divides ``p - 1``.
851
+ p : prime number
852
+ all_roots : if False returns the smallest root, else the list of roots
853
+
854
+ Returns
855
+ =======
856
+
857
+ list[int] | int :
858
+ Root of ``x**q = s mod p``. If ``all_roots == True``,
859
+ returned ascending list. otherwise, returned an int.
860
+
861
+ Examples
862
+ ========
863
+
864
+ >>> from sympy.ntheory.residue_ntheory import _nthroot_mod1
865
+ >>> _nthroot_mod1(5, 3, 13, False)
866
+ 7
867
+ >>> _nthroot_mod1(13, 4, 17, True)
868
+ [3, 5, 12, 14]
869
+
870
+ References
871
+ ==========
872
+
873
+ .. [1] A. M. Johnston, A Generalized qth Root Algorithm,
874
+ ACM-SIAM Symposium on Discrete Algorithms (1999), pp. 929-930
875
+
876
+ """
877
+ g = next(_primitive_root_prime_iter(p))
878
+ r = s
879
+ for qx, ex in factorint(q).items():
880
+ f = (p - 1) // qx**ex
881
+ while f % qx == 0:
882
+ f //= qx
883
+ z = f*invert(-f, qx)
884
+ x = (1 + z) // qx
885
+ t = discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
886
+ for _ in range(ex):
887
+ # assert t == discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
888
+ r = pow(r, x, p)*pow(g, -z*t % (p - 1), p) % p
889
+ t //= qx
890
+ res = [r]
891
+ h = pow(g, (p - 1) // q, p)
892
+ #assert pow(h, q, p) == 1
893
+ hx = r
894
+ for _ in range(q - 1):
895
+ hx = (hx*h) % p
896
+ res.append(hx)
897
+ if all_roots:
898
+ res.sort()
899
+ return res
900
+ return min(res)
901
+
902
+
903
+ def _nthroot_mod_prime_power(a, n, p, k):
904
+ """ Root of ``x**n = a mod p**k``.
905
+
906
+ Parameters
907
+ ==========
908
+
909
+ a : integer
910
+ n : integer, n > 2
911
+ p : prime number
912
+ k : positive integer
913
+
914
+ Returns
915
+ =======
916
+
917
+ list[int] :
918
+ Ascending list of roots of ``x**n = a mod p**k``.
919
+ If no solution exists, return ``[]``.
920
+
921
+ """
922
+ if not _is_nthpow_residue_bign_prime_power(a, n, p, k):
923
+ return []
924
+ a_mod_p = a % p
925
+ if a_mod_p == 0:
926
+ base_roots = [0]
927
+ elif (p - 1) % n == 0:
928
+ base_roots = _nthroot_mod1(a_mod_p, n, p, all_roots=True)
929
+ else:
930
+ # The roots of ``x**n - a = 0 (mod p)`` are roots of
931
+ # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
932
+ pa = n
933
+ pb = p - 1
934
+ b = 1
935
+ if pa < pb:
936
+ a_mod_p, pa, b, pb = b, pb, a_mod_p, pa
937
+ # gcd(x**pa - a, x**pb - b) = gcd(x**pb - b, x**pc - c)
938
+ # where pc = pa % pb; c = b**-q * a mod p
939
+ while pb:
940
+ q, pc = divmod(pa, pb)
941
+ c = pow(b, -q, p) * a_mod_p % p
942
+ pa, pb = pb, pc
943
+ a_mod_p, b = b, c
944
+ if pa == 1:
945
+ base_roots = [a_mod_p]
946
+ elif pa == 2:
947
+ base_roots = sqrt_mod(a_mod_p, p, all_roots=True)
948
+ else:
949
+ base_roots = _nthroot_mod1(a_mod_p, pa, p, all_roots=True)
950
+ if k == 1:
951
+ return base_roots
952
+ a %= p**k
953
+ tot_roots = set()
954
+ for root in base_roots:
955
+ diff = pow(root, n - 1, p)*n % p
956
+ new_base = p
957
+ if diff != 0:
958
+ m_inv = invert(diff, p)
959
+ for _ in range(k - 1):
960
+ new_base *= p
961
+ tmp = pow(root, n, new_base) - a
962
+ tmp *= m_inv
963
+ root = (root - tmp) % new_base
964
+ tot_roots.add(root)
965
+ else:
966
+ roots_in_base = {root}
967
+ for _ in range(k - 1):
968
+ new_base *= p
969
+ new_roots = set()
970
+ for k_ in roots_in_base:
971
+ if pow(k_, n, new_base) != a % new_base:
972
+ continue
973
+ while k_ not in new_roots:
974
+ new_roots.add(k_)
975
+ k_ = (k_ + (new_base // p)) % new_base
976
+ roots_in_base = new_roots
977
+ tot_roots = tot_roots | roots_in_base
978
+ return sorted(tot_roots)
979
+
980
+
981
+ def nthroot_mod(a, n, p, all_roots=False):
982
+ """
983
+ Find the solutions to ``x**n = a mod p``.
984
+
985
+ Parameters
986
+ ==========
987
+
988
+ a : integer
989
+ n : positive integer
990
+ p : positive integer
991
+ all_roots : if False returns the smallest root, else the list of roots
992
+
993
+ Returns
994
+ =======
995
+
996
+ list[int] | int | None :
997
+ solutions to ``x**n = a mod p``.
998
+ The table of the output type is:
999
+
1000
+ ========== ========== ==========
1001
+ all_roots has roots Returns
1002
+ ========== ========== ==========
1003
+ True Yes list[int]
1004
+ True No []
1005
+ False Yes int
1006
+ False No None
1007
+ ========== ========== ==========
1008
+
1009
+ Raises
1010
+ ======
1011
+
1012
+ ValueError
1013
+ If ``a``, ``n`` or ``p`` is not integer.
1014
+ If ``n`` or ``p`` is not positive.
1015
+
1016
+ Examples
1017
+ ========
1018
+
1019
+ >>> from sympy.ntheory.residue_ntheory import nthroot_mod
1020
+ >>> nthroot_mod(11, 4, 19)
1021
+ 8
1022
+ >>> nthroot_mod(11, 4, 19, True)
1023
+ [8, 11]
1024
+ >>> nthroot_mod(68, 3, 109)
1025
+ 23
1026
+
1027
+ References
1028
+ ==========
1029
+
1030
+ .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
1031
+
1032
+ """
1033
+ a = a % p
1034
+ a, n, p = as_int(a), as_int(n), as_int(p)
1035
+
1036
+ if n < 1:
1037
+ raise ValueError("n should be positive")
1038
+ if p < 1:
1039
+ raise ValueError("p should be positive")
1040
+ if n == 1:
1041
+ return [a] if all_roots else a
1042
+ if n == 2:
1043
+ return sqrt_mod(a, p, all_roots)
1044
+ base = []
1045
+ prime_power = []
1046
+ for q, e in factorint(p).items():
1047
+ tot_roots = _nthroot_mod_prime_power(a, n, q, e)
1048
+ if not tot_roots:
1049
+ return [] if all_roots else None
1050
+ prime_power.append(q**e)
1051
+ base.append(sorted(tot_roots))
1052
+ P, E, S = gf_crt1(prime_power, ZZ)
1053
+ ret = sorted(map(int, {gf_crt2(c, prime_power, P, E, S, ZZ)
1054
+ for c in product(*base)}))
1055
+ if all_roots:
1056
+ return ret
1057
+ if ret:
1058
+ return ret[0]
1059
+
1060
+
1061
+ def quadratic_residues(p) -> list[int]:
1062
+ """
1063
+ Returns the list of quadratic residues.
1064
+
1065
+ Examples
1066
+ ========
1067
+
1068
+ >>> from sympy.ntheory.residue_ntheory import quadratic_residues
1069
+ >>> quadratic_residues(7)
1070
+ [0, 1, 2, 4]
1071
+ """
1072
+ p = as_int(p)
1073
+ r = {pow(i, 2, p) for i in range(p // 2 + 1)}
1074
+ return sorted(r)
1075
+
1076
+
1077
+ @deprecated("""\
1078
+ The `sympy.ntheory.residue_ntheory.legendre_symbol` has been moved to `sympy.functions.combinatorial.numbers.legendre_symbol`.""",
1079
+ deprecated_since_version="1.13",
1080
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1081
+ def legendre_symbol(a, p):
1082
+ r"""
1083
+ Returns the Legendre symbol `(a / p)`.
1084
+
1085
+ .. deprecated:: 1.13
1086
+
1087
+ The ``legendre_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.legendre_symbol`
1088
+ instead. See its documentation for more information. See
1089
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1090
+
1091
+ For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
1092
+ defined as
1093
+
1094
+ .. math ::
1095
+ \genfrac(){}{}{a}{p} = \begin{cases}
1096
+ 0 & \text{if } p \text{ divides } a\\
1097
+ 1 & \text{if } a \text{ is a quadratic residue modulo } p\\
1098
+ -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
1099
+ \end{cases}
1100
+
1101
+ Parameters
1102
+ ==========
1103
+
1104
+ a : integer
1105
+ p : odd prime
1106
+
1107
+ Examples
1108
+ ========
1109
+
1110
+ >>> from sympy.functions.combinatorial.numbers import legendre_symbol
1111
+ >>> [legendre_symbol(i, 7) for i in range(7)]
1112
+ [0, 1, 1, -1, 1, -1, -1]
1113
+ >>> sorted(set([i**2 % 7 for i in range(7)]))
1114
+ [0, 1, 2, 4]
1115
+
1116
+ See Also
1117
+ ========
1118
+
1119
+ is_quad_residue, jacobi_symbol
1120
+
1121
+ """
1122
+ from sympy.functions.combinatorial.numbers import legendre_symbol as _legendre_symbol
1123
+ return _legendre_symbol(a, p)
1124
+
1125
+
1126
+ @deprecated("""\
1127
+ The `sympy.ntheory.residue_ntheory.jacobi_symbol` has been moved to `sympy.functions.combinatorial.numbers.jacobi_symbol`.""",
1128
+ deprecated_since_version="1.13",
1129
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1130
+ def jacobi_symbol(m, n):
1131
+ r"""
1132
+ Returns the Jacobi symbol `(m / n)`.
1133
+
1134
+ .. deprecated:: 1.13
1135
+
1136
+ The ``jacobi_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.jacobi_symbol`
1137
+ instead. See its documentation for more information. See
1138
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1139
+
1140
+ For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
1141
+ is defined as the product of the Legendre symbols corresponding to the
1142
+ prime factors of ``n``:
1143
+
1144
+ .. math ::
1145
+ \genfrac(){}{}{m}{n} =
1146
+ \genfrac(){}{}{m}{p^{1}}^{\alpha_1}
1147
+ \genfrac(){}{}{m}{p^{2}}^{\alpha_2}
1148
+ ...
1149
+ \genfrac(){}{}{m}{p^{k}}^{\alpha_k}
1150
+ \text{ where } n =
1151
+ p_1^{\alpha_1}
1152
+ p_2^{\alpha_2}
1153
+ ...
1154
+ p_k^{\alpha_k}
1155
+
1156
+ Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
1157
+ then ``m`` is a quadratic nonresidue modulo ``n``.
1158
+
1159
+ But, unlike the Legendre symbol, if the Jacobi symbol
1160
+ `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
1161
+ modulo ``n``.
1162
+
1163
+ Parameters
1164
+ ==========
1165
+
1166
+ m : integer
1167
+ n : odd positive integer
1168
+
1169
+ Examples
1170
+ ========
1171
+
1172
+ >>> from sympy.functions.combinatorial.numbers import jacobi_symbol, legendre_symbol
1173
+ >>> from sympy import S
1174
+ >>> jacobi_symbol(45, 77)
1175
+ -1
1176
+ >>> jacobi_symbol(60, 121)
1177
+ 1
1178
+
1179
+ The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
1180
+ be demonstrated as follows:
1181
+
1182
+ >>> L = legendre_symbol
1183
+ >>> S(45).factors()
1184
+ {3: 2, 5: 1}
1185
+ >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
1186
+ True
1187
+
1188
+ See Also
1189
+ ========
1190
+
1191
+ is_quad_residue, legendre_symbol
1192
+ """
1193
+ from sympy.functions.combinatorial.numbers import jacobi_symbol as _jacobi_symbol
1194
+ return _jacobi_symbol(m, n)
1195
+
1196
+
1197
+ @deprecated("""\
1198
+ The `sympy.ntheory.residue_ntheory.mobius` has been moved to `sympy.functions.combinatorial.numbers.mobius`.""",
1199
+ deprecated_since_version="1.13",
1200
+ active_deprecations_target='deprecated-ntheory-symbolic-functions')
1201
+ def mobius(n):
1202
+ """
1203
+ Mobius function maps natural number to {-1, 0, 1}
1204
+
1205
+ .. deprecated:: 1.13
1206
+
1207
+ The ``mobius`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.mobius`
1208
+ instead. See its documentation for more information. See
1209
+ :ref:`deprecated-ntheory-symbolic-functions` for details.
1210
+
1211
+ It is defined as follows:
1212
+ 1) `1` if `n = 1`.
1213
+ 2) `0` if `n` has a squared prime factor.
1214
+ 3) `(-1)^k` if `n` is a square-free positive integer with `k`
1215
+ number of prime factors.
1216
+
1217
+ It is an important multiplicative function in number theory
1218
+ and combinatorics. It has applications in mathematical series,
1219
+ algebraic number theory and also physics (Fermion operator has very
1220
+ concrete realization with Mobius Function model).
1221
+
1222
+ Parameters
1223
+ ==========
1224
+
1225
+ n : positive integer
1226
+
1227
+ Examples
1228
+ ========
1229
+
1230
+ >>> from sympy.functions.combinatorial.numbers import mobius
1231
+ >>> mobius(13*7)
1232
+ 1
1233
+ >>> mobius(1)
1234
+ 1
1235
+ >>> mobius(13*7*5)
1236
+ -1
1237
+ >>> mobius(13**2)
1238
+ 0
1239
+
1240
+ References
1241
+ ==========
1242
+
1243
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
1244
+ .. [2] Thomas Koshy "Elementary Number Theory with Applications"
1245
+
1246
+ """
1247
+ from sympy.functions.combinatorial.numbers import mobius as _mobius
1248
+ return _mobius(n)
1249
+
1250
+
1251
+ def _discrete_log_trial_mul(n, a, b, order=None):
1252
+ """
1253
+ Trial multiplication algorithm for computing the discrete logarithm of
1254
+ ``a`` to the base ``b`` modulo ``n``.
1255
+
1256
+ The algorithm finds the discrete logarithm using exhaustive search. This
1257
+ naive method is used as fallback algorithm of ``discrete_log`` when the
1258
+ group order is very small. The value ``n`` must be greater than 1.
1259
+
1260
+ Examples
1261
+ ========
1262
+
1263
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
1264
+ >>> _discrete_log_trial_mul(41, 15, 7)
1265
+ 3
1266
+
1267
+ See Also
1268
+ ========
1269
+
1270
+ discrete_log
1271
+
1272
+ References
1273
+ ==========
1274
+
1275
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1276
+ Vanstone, S. A. (1997).
1277
+ """
1278
+ a %= n
1279
+ b %= n
1280
+ if order is None:
1281
+ order = n
1282
+ x = 1
1283
+ for i in range(order):
1284
+ if x == a:
1285
+ return i
1286
+ x = x * b % n
1287
+ raise ValueError("Log does not exist")
1288
+
1289
+
1290
+ def _discrete_log_shanks_steps(n, a, b, order=None):
1291
+ """
1292
+ Baby-step giant-step algorithm for computing the discrete logarithm of
1293
+ ``a`` to the base ``b`` modulo ``n``.
1294
+
1295
+ The algorithm is a time-memory trade-off of the method of exhaustive
1296
+ search. It uses `O(sqrt(m))` memory, where `m` is the group order.
1297
+
1298
+ Examples
1299
+ ========
1300
+
1301
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
1302
+ >>> _discrete_log_shanks_steps(41, 15, 7)
1303
+ 3
1304
+
1305
+ See Also
1306
+ ========
1307
+
1308
+ discrete_log
1309
+
1310
+ References
1311
+ ==========
1312
+
1313
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1314
+ Vanstone, S. A. (1997).
1315
+ """
1316
+ a %= n
1317
+ b %= n
1318
+ if order is None:
1319
+ order = n_order(b, n)
1320
+ m = sqrt(order) + 1
1321
+ T = {}
1322
+ x = 1
1323
+ for i in range(m):
1324
+ T[x] = i
1325
+ x = x * b % n
1326
+ z = pow(b, -m, n)
1327
+ x = a
1328
+ for i in range(m):
1329
+ if x in T:
1330
+ return i * m + T[x]
1331
+ x = x * z % n
1332
+ raise ValueError("Log does not exist")
1333
+
1334
+
1335
+ def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
1336
+ """
1337
+ Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
1338
+ the base ``b`` modulo ``n``.
1339
+
1340
+ It is a randomized algorithm with the same expected running time as
1341
+ ``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
1342
+
1343
+ Examples
1344
+ ========
1345
+
1346
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
1347
+ >>> _discrete_log_pollard_rho(227, 3**7, 3)
1348
+ 7
1349
+
1350
+ See Also
1351
+ ========
1352
+
1353
+ discrete_log
1354
+
1355
+ References
1356
+ ==========
1357
+
1358
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1359
+ Vanstone, S. A. (1997).
1360
+ """
1361
+ a %= n
1362
+ b %= n
1363
+
1364
+ if order is None:
1365
+ order = n_order(b, n)
1366
+ randint = _randint(rseed)
1367
+
1368
+ for i in range(retries):
1369
+ aa = randint(1, order - 1)
1370
+ ba = randint(1, order - 1)
1371
+ xa = pow(b, aa, n) * pow(a, ba, n) % n
1372
+
1373
+ c = xa % 3
1374
+ if c == 0:
1375
+ xb = a * xa % n
1376
+ ab = aa
1377
+ bb = (ba + 1) % order
1378
+ elif c == 1:
1379
+ xb = xa * xa % n
1380
+ ab = (aa + aa) % order
1381
+ bb = (ba + ba) % order
1382
+ else:
1383
+ xb = b * xa % n
1384
+ ab = (aa + 1) % order
1385
+ bb = ba
1386
+
1387
+ for j in range(order):
1388
+ c = xa % 3
1389
+ if c == 0:
1390
+ xa = a * xa % n
1391
+ ba = (ba + 1) % order
1392
+ elif c == 1:
1393
+ xa = xa * xa % n
1394
+ aa = (aa + aa) % order
1395
+ ba = (ba + ba) % order
1396
+ else:
1397
+ xa = b * xa % n
1398
+ aa = (aa + 1) % order
1399
+
1400
+ c = xb % 3
1401
+ if c == 0:
1402
+ xb = a * xb % n
1403
+ bb = (bb + 1) % order
1404
+ elif c == 1:
1405
+ xb = xb * xb % n
1406
+ ab = (ab + ab) % order
1407
+ bb = (bb + bb) % order
1408
+ else:
1409
+ xb = b * xb % n
1410
+ ab = (ab + 1) % order
1411
+
1412
+ c = xb % 3
1413
+ if c == 0:
1414
+ xb = a * xb % n
1415
+ bb = (bb + 1) % order
1416
+ elif c == 1:
1417
+ xb = xb * xb % n
1418
+ ab = (ab + ab) % order
1419
+ bb = (bb + bb) % order
1420
+ else:
1421
+ xb = b * xb % n
1422
+ ab = (ab + 1) % order
1423
+
1424
+ if xa == xb:
1425
+ r = (ba - bb) % order
1426
+ try:
1427
+ e = invert(r, order) * (ab - aa) % order
1428
+ if (pow(b, e, n) - a) % n == 0:
1429
+ return e
1430
+ except ZeroDivisionError:
1431
+ pass
1432
+ break
1433
+ raise ValueError("Pollard's Rho failed to find logarithm")
1434
+
1435
+
1436
+ def _discrete_log_is_smooth(n: int, factorbase: list):
1437
+ """Try to factor n with respect to a given factorbase.
1438
+ Upon success a list of exponents with respect to the factorbase is returned.
1439
+ Otherwise None."""
1440
+ factors = [0]*len(factorbase)
1441
+ for i, p in enumerate(factorbase):
1442
+ while n % p == 0: # divide by p as many times as possible
1443
+ factors[i] += 1
1444
+ n = n // p
1445
+ if n != 1:
1446
+ return None # the number factors if at the end nothing is left
1447
+ return factors
1448
+
1449
+
1450
+ def _discrete_log_index_calculus(n, a, b, order, rseed=None):
1451
+ """
1452
+ Index Calculus algorithm for computing the discrete logarithm of ``a`` to
1453
+ the base ``b`` modulo ``n``.
1454
+
1455
+ The group order must be given and prime. It is not suitable for small orders
1456
+ and the algorithm might fail to find a solution in such situations.
1457
+
1458
+ Examples
1459
+ ========
1460
+
1461
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_index_calculus
1462
+ >>> _discrete_log_index_calculus(24570203447, 23859756228, 2, 12285101723)
1463
+ 4519867240
1464
+
1465
+ See Also
1466
+ ========
1467
+
1468
+ discrete_log
1469
+
1470
+ References
1471
+ ==========
1472
+
1473
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1474
+ Vanstone, S. A. (1997).
1475
+ """
1476
+ randint = _randint(rseed)
1477
+ from math import sqrt, exp, log
1478
+ a %= n
1479
+ b %= n
1480
+ # assert isprime(order), "The order of the base must be prime."
1481
+ # First choose a heuristic the bound B for the factorbase.
1482
+ # We have added an extra term to the asymptotic value which
1483
+ # is closer to the theoretical optimum for n up to 2^70.
1484
+ B = int(exp(0.5 * sqrt( log(n) * log(log(n)) )*( 1 + 1/log(log(n)) )))
1485
+ max = 5 * B * B # expected number of tries to find a relation
1486
+ factorbase = list(primerange(B)) # compute the factorbase
1487
+ lf = len(factorbase) # length of the factorbase
1488
+ ordermo = order-1
1489
+ abx = a
1490
+ for x in range(order):
1491
+ if abx == 1:
1492
+ return (order - x) % order
1493
+ relationa = _discrete_log_is_smooth(abx, factorbase)
1494
+ if relationa:
1495
+ relationa = [r % order for r in relationa] + [x]
1496
+ break
1497
+ abx = abx * b % n # abx = a*pow(b, x, n) % n
1498
+
1499
+ else:
1500
+ raise ValueError("Index Calculus failed")
1501
+
1502
+ relations = [None] * lf
1503
+ k = 1 # number of relations found
1504
+ kk = 0
1505
+ while k < 3 * lf and kk < max: # find relations for all primes in our factor base
1506
+ x = randint(1,ordermo)
1507
+ relation = _discrete_log_is_smooth(pow(b,x,n), factorbase)
1508
+ if relation is None:
1509
+ kk += 1
1510
+ continue
1511
+ k += 1
1512
+ kk = 0
1513
+ relation += [ x ]
1514
+ index = lf # determine the index of the first nonzero entry
1515
+ for i in range(lf):
1516
+ ri = relation[i] % order
1517
+ if ri> 0 and relations[i] is not None: # make this entry zero if we can
1518
+ for j in range(lf+1):
1519
+ relation[j] = (relation[j] - ri*relations[i][j]) % order
1520
+ else:
1521
+ relation[i] = ri
1522
+ if relation[i] > 0 and index == lf: # is this the index of the first nonzero entry?
1523
+ index = i
1524
+ if index == lf or relations[index] is not None: # the relation contains no new information
1525
+ continue
1526
+ # the relation contains new information
1527
+ rinv = pow(relation[index],-1,order) # normalize the first nonzero entry
1528
+ for j in range(index,lf+1):
1529
+ relation[j] = rinv * relation[j] % order
1530
+ relations[index] = relation
1531
+ for i in range(lf): # subtract the new relation from the one for a
1532
+ if relationa[i] > 0 and relations[i] is not None:
1533
+ rbi = relationa[i]
1534
+ for j in range(lf+1):
1535
+ relationa[j] = (relationa[j] - rbi*relations[i][j]) % order
1536
+ if relationa[i] > 0: # the index of the first nonzero entry
1537
+ break # we do not need to reduce further at this point
1538
+ else: # all unknowns are gone
1539
+ #print(f"Success after {k} relations out of {lf}")
1540
+ x = (order -relationa[lf]) % order
1541
+ if pow(b,x,n) == a:
1542
+ return x
1543
+ raise ValueError("Index Calculus failed")
1544
+ raise ValueError("Index Calculus failed")
1545
+
1546
+
1547
+ def _discrete_log_pohlig_hellman(n, a, b, order=None, order_factors=None):
1548
+ """
1549
+ Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
1550
+ the base ``b`` modulo ``n``.
1551
+
1552
+ In order to compute the discrete logarithm, the algorithm takes advantage
1553
+ of the factorization of the group order. It is more efficient when the
1554
+ group order factors into many small primes.
1555
+
1556
+ Examples
1557
+ ========
1558
+
1559
+ >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
1560
+ >>> _discrete_log_pohlig_hellman(251, 210, 71)
1561
+ 197
1562
+
1563
+ See Also
1564
+ ========
1565
+
1566
+ discrete_log
1567
+
1568
+ References
1569
+ ==========
1570
+
1571
+ .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1572
+ Vanstone, S. A. (1997).
1573
+ """
1574
+ from .modular import crt
1575
+ a %= n
1576
+ b %= n
1577
+
1578
+ if order is None:
1579
+ order = n_order(b, n)
1580
+ if order_factors is None:
1581
+ order_factors = factorint(order)
1582
+ l = [0] * len(order_factors)
1583
+
1584
+ for i, (pi, ri) in enumerate(order_factors.items()):
1585
+ for j in range(ri):
1586
+ aj = pow(a * pow(b, -l[i], n), order // pi**(j + 1), n)
1587
+ bj = pow(b, order // pi, n)
1588
+ cj = discrete_log(n, aj, bj, pi, True)
1589
+ l[i] += cj * pi**j
1590
+
1591
+ d, _ = crt([pi**ri for pi, ri in order_factors.items()], l)
1592
+ return d
1593
+
1594
+
1595
+ def discrete_log(n, a, b, order=None, prime_order=None):
1596
+ """
1597
+ Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
1598
+
1599
+ This is a recursive function to reduce the discrete logarithm problem in
1600
+ cyclic groups of composite order to the problem in cyclic groups of prime
1601
+ order.
1602
+
1603
+ It employs different algorithms depending on the problem (subgroup order
1604
+ size, prime order or not):
1605
+
1606
+ * Trial multiplication
1607
+ * Baby-step giant-step
1608
+ * Pollard's Rho
1609
+ * Index Calculus
1610
+ * Pohlig-Hellman
1611
+
1612
+ Examples
1613
+ ========
1614
+
1615
+ >>> from sympy.ntheory import discrete_log
1616
+ >>> discrete_log(41, 15, 7)
1617
+ 3
1618
+
1619
+ References
1620
+ ==========
1621
+
1622
+ .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
1623
+ .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
1624
+ Vanstone, S. A. (1997).
1625
+
1626
+ """
1627
+ from math import sqrt, log
1628
+ n, a, b = as_int(n), as_int(a), as_int(b)
1629
+
1630
+ if n < 1:
1631
+ raise ValueError("n should be positive")
1632
+ if n == 1:
1633
+ return 0
1634
+
1635
+ if order is None:
1636
+ # Compute the order and its factoring in one pass
1637
+ # order = totient(n), factors = factorint(order)
1638
+ factors = {}
1639
+ for px, kx in factorint(n).items():
1640
+ if kx > 1:
1641
+ if px in factors:
1642
+ factors[px] += kx - 1
1643
+ else:
1644
+ factors[px] = kx - 1
1645
+ for py, ky in factorint(px - 1).items():
1646
+ if py in factors:
1647
+ factors[py] += ky
1648
+ else:
1649
+ factors[py] = ky
1650
+ order = 1
1651
+ for px, kx in factors.items():
1652
+ order *= px**kx
1653
+ # Now the `order` is the order of the group and factors = factorint(order)
1654
+ # The order of `b` divides the order of the group.
1655
+ order_factors = {}
1656
+ for p, e in factors.items():
1657
+ i = 0
1658
+ for _ in range(e):
1659
+ if pow(b, order // p, n) == 1:
1660
+ order //= p
1661
+ i += 1
1662
+ else:
1663
+ break
1664
+ if i < e:
1665
+ order_factors[p] = e - i
1666
+
1667
+ if prime_order is None:
1668
+ prime_order = isprime(order)
1669
+
1670
+ if order < 1000:
1671
+ return _discrete_log_trial_mul(n, a, b, order)
1672
+ elif prime_order:
1673
+ # Shanks and Pollard rho are O(sqrt(order)) while index calculus is O(exp(2*sqrt(log(n)log(log(n)))))
1674
+ # we compare the expected running times to determine the algorithm which is expected to be faster
1675
+ if 4*sqrt(log(n)*log(log(n))) < log(order) - 10: # the number 10 was determined experimental
1676
+ return _discrete_log_index_calculus(n, a, b, order)
1677
+ elif order < 1000000000000:
1678
+ # Shanks seems typically faster, but uses O(sqrt(order)) memory
1679
+ return _discrete_log_shanks_steps(n, a, b, order)
1680
+ return _discrete_log_pollard_rho(n, a, b, order)
1681
+
1682
+ return _discrete_log_pohlig_hellman(n, a, b, order, order_factors)
1683
+
1684
+
1685
+
1686
+ def quadratic_congruence(a, b, c, n):
1687
+ r"""
1688
+ Find the solutions to `a x^2 + b x + c \equiv 0 \pmod{n}`.
1689
+
1690
+ Parameters
1691
+ ==========
1692
+
1693
+ a : int
1694
+ b : int
1695
+ c : int
1696
+ n : int
1697
+ A positive integer.
1698
+
1699
+ Returns
1700
+ =======
1701
+
1702
+ list[int] :
1703
+ A sorted list of solutions. If no solution exists, ``[]``.
1704
+
1705
+ Examples
1706
+ ========
1707
+
1708
+ >>> from sympy.ntheory.residue_ntheory import quadratic_congruence
1709
+ >>> quadratic_congruence(2, 5, 3, 7) # 2x^2 + 5x + 3 = 0 (mod 7)
1710
+ [2, 6]
1711
+ >>> quadratic_congruence(8, 6, 4, 15) # No solution
1712
+ []
1713
+
1714
+ See Also
1715
+ ========
1716
+
1717
+ polynomial_congruence : Solve the polynomial congruence
1718
+
1719
+ """
1720
+ a = as_int(a)
1721
+ b = as_int(b)
1722
+ c = as_int(c)
1723
+ n = as_int(n)
1724
+ if n <= 1:
1725
+ raise ValueError("n should be an integer greater than 1")
1726
+ a %= n
1727
+ b %= n
1728
+ c %= n
1729
+
1730
+ if a == 0:
1731
+ return linear_congruence(b, -c, n)
1732
+ if n == 2:
1733
+ # assert a == 1
1734
+ roots = []
1735
+ if c == 0:
1736
+ roots.append(0)
1737
+ if (b + c) % 2:
1738
+ roots.append(1)
1739
+ return roots
1740
+ if gcd(2*a, n) == 1:
1741
+ inv_a = invert(a, n)
1742
+ b *= inv_a
1743
+ c *= inv_a
1744
+ if b % 2:
1745
+ b += n
1746
+ b >>= 1
1747
+ return sorted((i - b) % n for i in sqrt_mod_iter(b**2 - c, n))
1748
+ res = set()
1749
+ for i in sqrt_mod_iter(b**2 - 4*a*c, 4*a*n):
1750
+ q, rem = divmod(i - b, 2*a)
1751
+ if rem == 0:
1752
+ res.add(q % n)
1753
+
1754
+ return sorted(res)
1755
+
1756
+
1757
+ def _valid_expr(expr):
1758
+ """
1759
+ return coefficients of expr if it is a univariate polynomial
1760
+ with integer coefficients else raise a ValueError.
1761
+ """
1762
+
1763
+ if not expr.is_polynomial():
1764
+ raise ValueError("The expression should be a polynomial")
1765
+ polynomial = Poly(expr)
1766
+ if not polynomial.is_univariate:
1767
+ raise ValueError("The expression should be univariate")
1768
+ if not polynomial.domain == ZZ:
1769
+ raise ValueError("The expression should should have integer coefficients")
1770
+ return polynomial.all_coeffs()
1771
+
1772
+
1773
+ def polynomial_congruence(expr, m):
1774
+ """
1775
+ Find the solutions to a polynomial congruence equation modulo m.
1776
+
1777
+ Parameters
1778
+ ==========
1779
+
1780
+ expr : integer coefficient polynomial
1781
+ m : positive integer
1782
+
1783
+ Examples
1784
+ ========
1785
+
1786
+ >>> from sympy.ntheory import polynomial_congruence
1787
+ >>> from sympy.abc import x
1788
+ >>> expr = x**6 - 2*x**5 -35
1789
+ >>> polynomial_congruence(expr, 6125)
1790
+ [3257]
1791
+
1792
+ See Also
1793
+ ========
1794
+
1795
+ sympy.polys.galoistools.gf_csolve : low level solving routine used by this routine
1796
+
1797
+ """
1798
+ coefficients = _valid_expr(expr)
1799
+ coefficients = [num % m for num in coefficients]
1800
+ rank = len(coefficients)
1801
+ if rank == 3:
1802
+ return quadratic_congruence(*coefficients, m)
1803
+ if rank == 2:
1804
+ return quadratic_congruence(0, *coefficients, m)
1805
+ if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients):
1806
+ return nthroot_mod(-coefficients[-1], rank - 1, m, True)
1807
+ return gf_csolve(coefficients, m)
1808
+
1809
+
1810
+ def binomial_mod(n, m, k):
1811
+ """Compute ``binomial(n, m) % k``.
1812
+
1813
+ Explanation
1814
+ ===========
1815
+
1816
+ Returns ``binomial(n, m) % k`` using a generalization of Lucas'
1817
+ Theorem for prime powers given by Granville [1]_, in conjunction with
1818
+ the Chinese Remainder Theorem. The residue for each prime power
1819
+ is calculated in time O(log^2(n) + q^4*log(n)log(p) + q^4*p*log^3(p)).
1820
+
1821
+ Parameters
1822
+ ==========
1823
+
1824
+ n : an integer
1825
+ m : an integer
1826
+ k : a positive integer
1827
+
1828
+ Examples
1829
+ ========
1830
+
1831
+ >>> from sympy.ntheory.residue_ntheory import binomial_mod
1832
+ >>> binomial_mod(10, 2, 6) # binomial(10, 2) = 45
1833
+ 3
1834
+ >>> binomial_mod(17, 9, 10) # binomial(17, 9) = 24310
1835
+ 0
1836
+
1837
+ References
1838
+ ==========
1839
+
1840
+ .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
1841
+ Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
1842
+ """
1843
+ if k < 1: raise ValueError('k is required to be positive')
1844
+ # We decompose q into a product of prime powers and apply
1845
+ # the generalization of Lucas' Theorem given by Granville
1846
+ # to obtain binomial(n, k) mod p^e, and then use the Chinese
1847
+ # Remainder Theorem to obtain the result mod q
1848
+ if n < 0 or m < 0 or m > n: return 0
1849
+ factorisation = factorint(k)
1850
+ residues = [_binomial_mod_prime_power(n, m, p, e) for p, e in factorisation.items()]
1851
+ return crt([p**pw for p, pw in factorisation.items()], residues, check=False)[0]
1852
+
1853
+
1854
+ def _binomial_mod_prime_power(n, m, p, q):
1855
+ """Compute ``binomial(n, m) % p**q`` for a prime ``p``.
1856
+
1857
+ Parameters
1858
+ ==========
1859
+
1860
+ n : positive integer
1861
+ m : a nonnegative integer
1862
+ p : a prime
1863
+ q : a positive integer (the prime exponent)
1864
+
1865
+ Examples
1866
+ ========
1867
+
1868
+ >>> from sympy.ntheory.residue_ntheory import _binomial_mod_prime_power
1869
+ >>> _binomial_mod_prime_power(10, 2, 3, 2) # binomial(10, 2) = 45
1870
+ 0
1871
+ >>> _binomial_mod_prime_power(17, 9, 2, 4) # binomial(17, 9) = 24310
1872
+ 6
1873
+
1874
+ References
1875
+ ==========
1876
+
1877
+ .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
1878
+ Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
1879
+ """
1880
+ # Function/variable naming within this function follows Ref.[1]
1881
+ # n!_p will be used to denote the product of integers <= n not divisible by
1882
+ # p, with binomial(n, m)_p the same as binomial(n, m), but defined using
1883
+ # n!_p in place of n!
1884
+ modulo = pow(p, q)
1885
+
1886
+ def up_factorial(u):
1887
+ """Compute (u*p)!_p modulo p^q."""
1888
+ r = q // 2
1889
+ fac = prod = 1
1890
+ if r == 1 and p == 2 or 2*r + 1 in (p, p*p):
1891
+ if q % 2 == 1: r += 1
1892
+ modulo, div = pow(p, 2*r), pow(p, 2*r - q)
1893
+ else:
1894
+ modulo, div = pow(p, 2*r + 1), pow(p, (2*r + 1) - q)
1895
+ for j in range(1, r + 1):
1896
+ for mul in range((j - 1)*p + 1, j*p): # ignore jp itself
1897
+ fac *= mul
1898
+ fac %= modulo
1899
+ bj_ = bj(u, j, r)
1900
+ prod *= pow(fac, bj_, modulo)
1901
+ prod %= modulo
1902
+ if p == 2:
1903
+ sm = u // 2
1904
+ for j in range(1, r + 1): sm += j//2 * bj(u, j, r)
1905
+ if sm % 2 == 1: prod *= -1
1906
+ prod %= modulo//div
1907
+ return prod % modulo
1908
+
1909
+ def bj(u, j, r):
1910
+ """Compute the exponent of (j*p)!_p in the calculation of (u*p)!_p."""
1911
+ prod = u
1912
+ for i in range(1, r + 1):
1913
+ if i != j: prod *= u*u - i*i
1914
+ for i in range(1, r + 1):
1915
+ if i != j: prod //= j*j - i*i
1916
+ return prod // j
1917
+
1918
+ def up_plus_v_binom(u, v):
1919
+ """Compute binomial(u*p + v, v)_p modulo p^q."""
1920
+ prod = 1
1921
+ div = invert(factorial(v), modulo)
1922
+ for j in range(1, q):
1923
+ b = div
1924
+ for v_ in range(j*p + 1, j*p + v + 1):
1925
+ b *= v_
1926
+ b %= modulo
1927
+ aj = u
1928
+ for i in range(1, q):
1929
+ if i != j: aj *= u - i
1930
+ for i in range(1, q):
1931
+ if i != j: aj //= j - i
1932
+ aj //= j
1933
+ prod *= pow(b, aj, modulo)
1934
+ prod %= modulo
1935
+ return prod
1936
+
1937
+ @recurrence_memo([1])
1938
+ def factorial(v, prev):
1939
+ """Compute v! modulo p^q."""
1940
+ return v*prev[-1] % modulo
1941
+
1942
+ def factorial_p(n):
1943
+ """Compute n!_p modulo p^q."""
1944
+ u, v = divmod(n, p)
1945
+ return (factorial(v) * up_factorial(u) * up_plus_v_binom(u, v)) % modulo
1946
+
1947
+ prod = 1
1948
+ Nj, Mj, Rj = n, m, n - m
1949
+ # e0 will be the p-adic valuation of binomial(n, m) at p
1950
+ e0 = carry = eq_1 = j = 0
1951
+ while Nj:
1952
+ numerator = factorial_p(Nj % modulo)
1953
+ denominator = factorial_p(Mj % modulo) * factorial_p(Rj % modulo) % modulo
1954
+ Nj, (Mj, mj), (Rj, rj) = Nj//p, divmod(Mj, p), divmod(Rj, p)
1955
+ carry = (mj + rj + carry) // p
1956
+ e0 += carry
1957
+ if j >= q - 1: eq_1 += carry
1958
+ prod *= numerator * invert(denominator, modulo)
1959
+ prod %= modulo
1960
+ j += 1
1961
+
1962
+ mul = pow(1 if p == 2 and q >= 3 else -1, eq_1, modulo)
1963
+ return (pow(p, e0, modulo) * mul * prod) % modulo
.venv/Lib/site-packages/sympy/ntheory/tests/__init__.py ADDED
File without changes
.venv/Lib/site-packages/sympy/ntheory/tests/test_bbp_pi.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.random import randint
2
+
3
+ from sympy.ntheory.bbp_pi import pi_hex_digits
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ # http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
8
+ # There are actually 8336 listed there; with the prepended 3 there are 8337
9
+ # below
10
+ dig=''.join('''
11
+ 3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
12
+ 77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
13
+ ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
14
+ 16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
15
+ b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
16
+ 3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
17
+ b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
18
+ 1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
19
+ 91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
20
+ 392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
21
+ 68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
22
+ 888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
23
+ 061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
24
+ f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
25
+ b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
26
+ b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
27
+ cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
28
+ 829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
29
+ c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
30
+ 90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
31
+ 98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
32
+ 1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
33
+ e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
34
+ 77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
35
+ 5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
36
+ c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
37
+ e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
38
+ 6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
39
+ 7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
40
+ 3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
41
+ 266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
42
+ 373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
43
+ b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
44
+ a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
45
+ 086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
46
+ 2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
47
+ fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
48
+ dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
49
+ fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
50
+ 0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
51
+ 3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
52
+ 28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
53
+ 70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
54
+ 14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
55
+ b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
56
+ 810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
57
+ 548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
58
+ e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
59
+ c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
60
+ 85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
61
+ 41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
62
+ 35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
63
+ cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
64
+ f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
65
+ 6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
66
+ 45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
67
+ f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
68
+ b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
69
+ 5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
70
+ 2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
71
+ f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
72
+ dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
73
+ 60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
74
+ 2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
75
+ fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
76
+ 0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
77
+ 9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
78
+ 2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
79
+ fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
80
+ fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
81
+ 71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
82
+ c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
83
+ 708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
84
+ 33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
85
+ fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
86
+ b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
87
+ deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
88
+ fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
89
+ c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
90
+ 1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
91
+ 45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
92
+ c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
93
+ f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
94
+ e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
95
+ 972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
96
+ 4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
97
+ 55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
98
+ 2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
99
+ f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
100
+ 32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
101
+ dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
102
+ d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
103
+ 57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
104
+ 486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
105
+ 4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
106
+ 380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
107
+ 2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
108
+ 42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
109
+ 8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
110
+ 6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
111
+ b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
112
+ 9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
113
+ d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
114
+ 7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
115
+ 5b578fdfe33ac372e6'''.split())
116
+
117
+
118
+ def test_hex_pi_nth_digits():
119
+ assert pi_hex_digits(0) == '3243f6a8885a30'
120
+ assert pi_hex_digits(1) == '243f6a8885a308'
121
+ assert pi_hex_digits(10000) == '68ac8fcfb8016c'
122
+ assert pi_hex_digits(13) == '08d313198a2e03'
123
+ assert pi_hex_digits(0, 3) == '324'
124
+ assert pi_hex_digits(0, 0) == ''
125
+ raises(ValueError, lambda: pi_hex_digits(-1))
126
+ raises(ValueError, lambda: pi_hex_digits(0, -1))
127
+ raises(ValueError, lambda: pi_hex_digits(3.14))
128
+
129
+ # this will pick a random segment to compute every time
130
+ # it is run. If it ever fails, there is an error in the
131
+ # computation.
132
+ n = randint(0, len(dig))
133
+ prec = randint(0, len(dig) - n)
134
+ assert pi_hex_digits(n, prec) == dig[n: n + prec]
.venv/Lib/site-packages/sympy/ntheory/tests/test_continued_fraction.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from sympy.core import GoldenRatio as phi
3
+ from sympy.core.numbers import (Rational, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.ntheory.continued_fraction import \
7
+ (continued_fraction_periodic as cf_p,
8
+ continued_fraction_iterator as cf_i,
9
+ continued_fraction_convergents as cf_c,
10
+ continued_fraction_reduce as cf_r,
11
+ continued_fraction as cf)
12
+ from sympy.testing.pytest import raises
13
+
14
+
15
+ def test_continued_fraction():
16
+ assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1)
17
+ assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1)
18
+ t = sqrt(2)
19
+ assert cf((1 + t)*(1 - t)) == cf(-1)
20
+ for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5,
21
+ (2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]:
22
+ assert (cf_r(cf(n)) - n).expand() == 0
23
+ assert (cf_r(cf(-n)) + n).expand() == 0
24
+ raises(ValueError, lambda: cf(sqrt(2 + sqrt(3))))
25
+ raises(ValueError, lambda: cf(sqrt(2) + sqrt(3)))
26
+ raises(ValueError, lambda: cf(pi))
27
+ raises(ValueError, lambda: cf(.1))
28
+
29
+ raises(ValueError, lambda: cf_p(1, 0, 0))
30
+ raises(ValueError, lambda: cf_p(1, 1, -1))
31
+ assert cf_p(4, 3, 0) == [1, 3]
32
+ assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
33
+ assert cf_p(1, 1, 0) == [1]
34
+ assert cf_p(3, 4, 0) == [0, 1, 3]
35
+ assert cf_p(4, 5, 0) == [0, 1, 4]
36
+ assert cf_p(5, 6, 0) == [0, 1, 5]
37
+ assert cf_p(11, 13, 0) == [0, 1, 5, 2]
38
+ assert cf_p(16, 19, 0) == [0, 1, 5, 3]
39
+ assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
40
+ assert cf_p(1, 2, 5) == [[1]]
41
+ assert cf_p(0, 1, 2) == [1, [2]]
42
+ assert cf_p(6, 7, 49) == [1, 1, 6]
43
+ assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
44
+ assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
45
+ assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
46
+ assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
47
+
48
+ def take(iterator, n=7):
49
+ return list(itertools.islice(iterator, n))
50
+
51
+ assert take(cf_i(phi)) == [1, 1, 1, 1, 1, 1, 1]
52
+ assert take(cf_i(pi)) == [3, 7, 15, 1, 292, 1, 1]
53
+
54
+ assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2]
55
+ assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2]
56
+
57
+ assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)]
58
+ assert list(cf_c([2])) == [S(2)]
59
+ assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3),
60
+ Rational(8, 5), Rational(13, 8), Rational(21, 13)]
61
+ assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)]
62
+ assert take(cf_c([[1]])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), Rational(8, 5),
63
+ Rational(13, 8), Rational(21, 13)]
64
+ assert take(cf_c([1, [1, 2]])) == [S.One, S(2), Rational(5, 3), Rational(7, 4), Rational(19, 11),
65
+ Rational(26, 15), Rational(71, 41)]
66
+
67
+ cf_iter_e = (2 if i == 1 else i // 3 * 2 if i % 3 == 0 else 1 for i in itertools.count(1))
68
+ assert take(cf_c(cf_iter_e)) == [S(2), S(3), Rational(8, 3), Rational(11, 4), Rational(19, 7),
69
+ Rational(87, 32), Rational(106, 39)]
70
+
71
+ assert cf_r([1, 6, 1, 8]) == Rational(71, 62)
72
+ assert cf_r([3]) == S(3)
73
+ assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29)
74
+ assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
75
+ assert cf_r([1, 5, 9]) == Rational(55, 46)
76
+ assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
77
+ assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2)
.venv/Lib/site-packages/sympy/ntheory/tests/test_digits.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory import count_digits, digits, is_palindromic
2
+ from sympy.core.intfunc import num_digits
3
+
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ def test_num_digits():
8
+ # depending on whether one rounds up or down or uses log or log10,
9
+ # one or more of these will fail if you don't check for the off-by
10
+ # one condition
11
+ assert num_digits(2, 2) == 2
12
+ assert num_digits(2**48 - 1, 2) == 48
13
+ assert num_digits(1000, 10) == 4
14
+ assert num_digits(125, 5) == 4
15
+ assert num_digits(100, 16) == 2
16
+ assert num_digits(-1000, 10) == 4
17
+ # if changes are made to the function, this structured test over
18
+ # this range will expose problems
19
+ for base in range(2, 100):
20
+ for e in range(1, 100):
21
+ n = base**e
22
+ assert num_digits(n, base) == e + 1
23
+ assert num_digits(n + 1, base) == e + 1
24
+ assert num_digits(n - 1, base) == e
25
+
26
+
27
+ def test_digits():
28
+ assert all(digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
29
+ for n in range(20))
30
+ assert all(digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
31
+ for n in range(20))
32
+ assert all(digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
33
+ for n in range(20))
34
+ assert digits(2345, 34) == [34, 2, 0, 33]
35
+ assert digits(384753, 71) == [71, 1, 5, 23, 4]
36
+ assert digits(93409, 10) == [10, 9, 3, 4, 0, 9]
37
+ assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
38
+ assert digits(35, 10) == [10, 3, 5]
39
+ assert digits(35, 10, 3) == [10, 0, 3, 5]
40
+ assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5]
41
+ raises(ValueError, lambda: digits(2, 2, 1))
42
+
43
+
44
+ def test_count_digits():
45
+ assert count_digits(55, 2) == {1: 5, 0: 1}
46
+ assert count_digits(55, 10) == {5: 2}
47
+ n = count_digits(123)
48
+ assert n[4] == 0 and type(n[4]) is int
49
+
50
+
51
+ def test_is_palindromic():
52
+ assert is_palindromic(-11)
53
+ assert is_palindromic(11)
54
+ assert is_palindromic(0o121, 8)
55
+ assert not is_palindromic(123)
.venv/Lib/site-packages/sympy/ntheory/tests/test_ecm.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external.gmpy import invert
2
+ from sympy.ntheory.ecm import ecm, Point
3
+ from sympy.testing.pytest import slow
4
+
5
+ @slow
6
+ def test_ecm():
7
+ assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297}
8
+ assert ecm(46167045131415113) == {43, 2634823, 407485517}
9
+ assert ecm(631211032315670776841) == {9312934919, 67777885039}
10
+ assert ecm(398883434337287) == {99476569, 4009823}
11
+ assert ecm(64211816600515193) == {281719, 359641, 633767}
12
+ assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123}
13
+ assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571}
14
+ assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803}
15
+ assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721}
16
+ #This takes ~10secs while factorint is not able to factorize this even in ~10mins
17
+ assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809}
18
+
19
+
20
+ def test_Point():
21
+ #The curve is of the form y**2 = x**3 + a*x**2 + x
22
+ mod = 101
23
+ a = 10
24
+ a_24 = (a + 2)*invert(4, mod)
25
+ p1 = Point(10, 17, a_24, mod)
26
+ p2 = p1.double()
27
+ assert p2 == Point(68, 56, a_24, mod)
28
+ p4 = p2.double()
29
+ assert p4 == Point(22, 64, a_24, mod)
30
+ p8 = p4.double()
31
+ assert p8 == Point(71, 95, a_24, mod)
32
+ p16 = p8.double()
33
+ assert p16 == Point(5, 16, a_24, mod)
34
+ p32 = p16.double()
35
+ assert p32 == Point(33, 96, a_24, mod)
36
+
37
+ # p3 = p2 + p1
38
+ p3 = p2.add(p1, p1)
39
+ assert p3 == Point(1, 61, a_24, mod)
40
+ # p5 = p3 + p2 or p4 + p1
41
+ p5 = p3.add(p2, p1)
42
+ assert p5 == Point(49, 90, a_24, mod)
43
+ assert p5 == p4.add(p1, p3)
44
+ # p6 = 2*p3
45
+ p6 = p3.double()
46
+ assert p6 == Point(87, 43, a_24, mod)
47
+ assert p6 == p4.add(p2, p2)
48
+ # p7 = p5 + p2
49
+ p7 = p5.add(p2, p3)
50
+ assert p7 == Point(69, 23, a_24, mod)
51
+ assert p7 == p4.add(p3, p1)
52
+ assert p7 == p6.add(p1, p5)
53
+ # p9 = p5 + p4
54
+ p9 = p5.add(p4, p1)
55
+ assert p9 == Point(56, 99, a_24, mod)
56
+ assert p9 == p6.add(p3, p3)
57
+ assert p9 == p7.add(p2, p5)
58
+ assert p9 == p8.add(p1, p7)
59
+
60
+ assert p5 == p1.mont_ladder(5)
61
+ assert p9 == p1.mont_ladder(9)
62
+ assert p16 == p1.mont_ladder(16)
63
+ assert p9 == p3.mont_ladder(3)
.venv/Lib/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.ntheory.egyptian_fraction import egyptian_fraction
3
+ from sympy.core.add import Add
4
+ from sympy.testing.pytest import raises
5
+ from sympy.core.random import random_complex_number
6
+
7
+
8
+ def test_egyptian_fraction():
9
+ def test_equality(r, alg="Greedy"):
10
+ return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)])
11
+
12
+ r = random_complex_number(a=0, c=1, b=0, d=0, rational=True)
13
+ assert test_equality(r)
14
+
15
+ assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345]
16
+ assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26]
17
+ assert egyptian_fraction(Rational(23, 101), "Greedy") == \
18
+ [5, 37, 1438, 2985448, 40108045937720]
19
+ assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \
20
+ [2, 6, 12, 35, 276, 2415]
21
+ assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \
22
+ [6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807,
23
+ 1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443,
24
+ 3267056, 3581556, 10192056, 10650056950806]
25
+ assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30]
26
+ assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737]
27
+ raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9)))
28
+ assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7,
29
+ 14, 574, 2788, 6460,
30
+ 11590, 33062, 113820]
31
+ assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9,
32
+ 10, 11, 12, 27, 744, 893588,
33
+ 1251493536607,
34
+ 20361068938197002344405230]
35
+
36
+
37
+ def test_input():
38
+ r = (2,3), Rational(2, 3), (Rational(2), Rational(3))
39
+ for m in ["Greedy", "Graham Jewett", "Takenouchi", "Golomb"]:
40
+ for i in r:
41
+ d = egyptian_fraction(i, m)
42
+ assert all(i.is_Integer for i in d)
43
+ if m == "Graham Jewett":
44
+ assert d == [3, 4, 12]
45
+ else:
46
+ assert d == [2, 6]
47
+ # check prefix
48
+ d = egyptian_fraction(Rational(5, 3))
49
+ assert d == [1, 2, 6] and all(i.is_Integer for i in d)
.venv/Lib/site-packages/sympy/ntheory/tests/test_elliptic_curve.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.elliptic_curve import EllipticCurve
2
+
3
+
4
+ def test_elliptic_curve():
5
+ # Point addition and multiplication
6
+ e3 = EllipticCurve(-1, 9)
7
+ p = e3(0, 3)
8
+ q = e3(-1, 3)
9
+ r = p + q
10
+ assert r.x == 1 and r.y == -3
11
+ r = 2*p + q
12
+ assert r.x == 35 and r.y == 207
13
+ r = -p + q
14
+ assert r.x == 37 and r.y == 225
15
+ # Verify result in http://www.lmfdb.org/EllipticCurve/Q
16
+ # Discriminant
17
+ assert EllipticCurve(-1, 9).discriminant == -34928
18
+ assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088
19
+ # Torsion points
20
+ assert len(EllipticCurve(0, 1).torsion_points()) == 6
.venv/Lib/site-packages/sympy/ntheory/tests/test_factor_.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Dict
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.power import Pow
4
+ from sympy.core.singleton import S
5
+ from sympy.functions.combinatorial.factorials import factorial as fac
6
+ from sympy.core.numbers import Integer, Rational
7
+ from sympy.external.gmpy import gcd
8
+
9
+ from sympy.ntheory import (totient,
10
+ factorint, primefactors, divisors, nextprime,
11
+ pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial,
12
+ divisor_count, primorial, pollard_pm1, divisor_sigma,
13
+ factorrat, reduced_totient)
14
+ from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors,
15
+ antidivisors, antidivisor_count, _divisor_sigma, core, udivisors, udivisor_sigma,
16
+ udivisor_count, proper_divisor_count, primenu, primeomega,
17
+ mersenne_prime_exponent, is_perfect, is_abundant,
18
+ is_deficient, is_amicable, is_carmichael, find_carmichael_numbers_in_range,
19
+ find_first_n_carmichaels, dra, drm, _perfect_power, factor_cache)
20
+
21
+ from sympy.testing.pytest import raises, slow
22
+
23
+ from sympy.utilities.iterables import capture
24
+
25
+
26
+ def fac_multiplicity(n, p):
27
+ """Return the power of the prime number p in the
28
+ factorization of n!"""
29
+ if p > n:
30
+ return 0
31
+ if p > n//2:
32
+ return 1
33
+ q, m = n, 0
34
+ while q >= p:
35
+ q //= p
36
+ m += q
37
+ return m
38
+
39
+
40
+ def multiproduct(seq=(), start=1):
41
+ """
42
+ Return the product of a sequence of factors with multiplicities,
43
+ times the value of the parameter ``start``. The input may be a
44
+ sequence of (factor, exponent) pairs or a dict of such pairs.
45
+
46
+ >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
47
+ 279936
48
+
49
+ """
50
+ if not seq:
51
+ return start
52
+ if isinstance(seq, dict):
53
+ seq = iter(seq.items())
54
+ units = start
55
+ multi = []
56
+ for base, exp in seq:
57
+ if not exp:
58
+ continue
59
+ elif exp == 1:
60
+ units *= base
61
+ else:
62
+ if exp % 2:
63
+ units *= base
64
+ multi.append((base, exp//2))
65
+ return units * multiproduct(multi)**2
66
+
67
+
68
+ def test_multiplicity():
69
+ for b in range(2, 20):
70
+ for i in range(100):
71
+ assert multiplicity(b, b**i) == i
72
+ assert multiplicity(b, (b**i) * 23) == i
73
+ assert multiplicity(b, (b**i) * 1000249) == i
74
+ # Should be fast
75
+ assert multiplicity(10, 10**10023) == 10023
76
+ # Should exit quickly
77
+ assert multiplicity(10**10, 10**10) == 1
78
+ # Should raise errors for bad input
79
+ raises(ValueError, lambda: multiplicity(1, 1))
80
+ raises(ValueError, lambda: multiplicity(1, 2))
81
+ raises(ValueError, lambda: multiplicity(1.3, 2))
82
+ raises(ValueError, lambda: multiplicity(2, 0))
83
+ raises(ValueError, lambda: multiplicity(1.3, 0))
84
+
85
+ # handles Rationals
86
+ assert multiplicity(10, Rational(30, 7)) == 1
87
+ assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
88
+ assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
89
+ assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
90
+ assert multiplicity(3, Rational(1, 9)) == -2
91
+
92
+
93
+ def test_multiplicity_in_factorial():
94
+ n = fac(1000)
95
+ for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96):
96
+ assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000)
97
+
98
+
99
+ def test_private_perfect_power():
100
+ assert _perfect_power(0) is False
101
+ assert _perfect_power(1) is False
102
+ assert _perfect_power(2) is False
103
+ assert _perfect_power(3) is False
104
+ for x in [2, 3, 5, 6, 7, 12, 15, 105, 100003]:
105
+ for y in range(2, 100):
106
+ assert _perfect_power(x**y) == (x, y)
107
+ if x & 1:
108
+ assert _perfect_power(x**y, next_p=3) == (x, y)
109
+ if x == 100003:
110
+ assert _perfect_power(x**y, next_p=100003) == (x, y)
111
+ assert _perfect_power(101*x**y) == False
112
+ # Catalan's conjecture
113
+ if x**y not in [8, 9]:
114
+ assert _perfect_power(x**y + 1) == False
115
+ assert _perfect_power(x**y - 1) == False
116
+ for x in range(1, 10):
117
+ for y in range(1, 10):
118
+ g = gcd(x, y)
119
+ if g == 1:
120
+ assert _perfect_power(5**x * 101**y) == False
121
+ else:
122
+ assert _perfect_power(5**x * 101**y) == (5**(x//g) * 101**(y//g), g)
123
+
124
+
125
+ def test_perfect_power():
126
+ raises(ValueError, lambda: perfect_power(0.1))
127
+ assert perfect_power(0) is False
128
+ assert perfect_power(1) is False
129
+ assert perfect_power(2) is False
130
+ assert perfect_power(3) is False
131
+ assert perfect_power(4) == (2, 2)
132
+ assert perfect_power(14) is False
133
+ assert perfect_power(25) == (5, 2)
134
+ assert perfect_power(22) is False
135
+ assert perfect_power(22, [2]) is False
136
+ assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
137
+ assert perfect_power(137**(3*5*13) + 1) is False
138
+ assert perfect_power(137**(3*5*13) - 1) is False
139
+ assert perfect_power(103005006004**7) == (103005006004, 7)
140
+ assert perfect_power(103005006004**7 + 1) is False
141
+ assert perfect_power(103005006004**7 - 1) is False
142
+ assert perfect_power(103005006004**12) == (103005006004, 12)
143
+ assert perfect_power(103005006004**12 + 1) is False
144
+ assert perfect_power(103005006004**12 - 1) is False
145
+ assert perfect_power(2**10007) == (2, 10007)
146
+ assert perfect_power(2**10007 + 1) is False
147
+ assert perfect_power(2**10007 - 1) is False
148
+ assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
149
+ assert perfect_power((9**99 + 1)**60 + 1) is False
150
+ assert perfect_power((9**99 + 1)**60 - 1) is False
151
+ assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
152
+ assert perfect_power(10**100000) == (10, 100000)
153
+ assert perfect_power(10**100001) == (10, 100001)
154
+ assert perfect_power(13**4, [3, 5]) is False
155
+ assert perfect_power(3**4, [3, 10], factor=0) is False
156
+ assert perfect_power(3**3*5**3) == (15, 3)
157
+ assert perfect_power(2**3*5**5) is False
158
+ assert perfect_power(2*13**4) is False
159
+ assert perfect_power(2**5*3**3) is False
160
+ t = 2**24
161
+ for d in divisors(24):
162
+ m = perfect_power(t*3**d)
163
+ assert m and m[1] == d or d == 1
164
+ m = perfect_power(t*3**d, big=False)
165
+ assert m and m[1] == 2 or d == 1 or d == 3, (d, m)
166
+
167
+ # negatives and non-integer rationals
168
+ assert perfect_power(-4) is False
169
+ assert perfect_power(-8) == (-2, 3)
170
+ assert perfect_power(-S(1)/8) == (-S(1)/2, 3)
171
+ assert perfect_power(S(1)/3) == False
172
+ assert perfect_power(-5**15) == (-5, 15)
173
+ assert perfect_power(-5**15, big=False) == (-3125, 3)
174
+ assert perfect_power(-5**15, [15]) == (-5, 15)
175
+
176
+ n = -3 ** 60
177
+ assert perfect_power(n) == (-81, 15)
178
+ assert perfect_power(n, big=False) == (-3486784401, 3)
179
+ assert perfect_power(n, [3, 5], big=True) == (-531441, 5)
180
+ assert perfect_power(n, [3, 5], big=False) == (-3486784401, 3)
181
+ assert perfect_power(n, [2]) == False
182
+ assert perfect_power(n, [2, 15]) == (-81, 15)
183
+ assert perfect_power(n, [2, 13]) == False
184
+ assert perfect_power(n, [17]) == False
185
+ assert perfect_power(n, [3]) == (-3486784401, 3)
186
+ assert perfect_power(n + 1) == False
187
+
188
+ r = S(2) ** (2 * 5 * 7) / S(3) ** (2 * 7)
189
+ assert perfect_power(r) == (S(32) / 3, 14)
190
+ assert perfect_power(-r) == (-S(1024) / 9, 7)
191
+ assert perfect_power(r, big=False) == (S(34359738368) / 2187, 2)
192
+ assert perfect_power(r, [2, 5]) == (S(34359738368) / 2187, 2)
193
+ assert perfect_power(r, [5, 7]) == (S(1024) / 9, 7)
194
+ assert perfect_power(r, [5, 7], big=False) == (S(1024) / 9, 7)
195
+ assert perfect_power(r, [2, 5, 7], big=False) == (S(34359738368) / 2187, 2)
196
+ assert perfect_power(-r, [5, 7], big=False) == (-S(1024) / 9, 7)
197
+
198
+ assert perfect_power(-S(1) / 8) == (-S(1) / 2, 3)
199
+
200
+ assert perfect_power((-3)**60) == (3, 60)
201
+ assert perfect_power((-3)**61) == (-3, 61)
202
+
203
+ assert perfect_power(S(2 ** 9) / 3 ** 12) == (S(8)/81, 3)
204
+ assert perfect_power(Rational(1, 2)**3) == (S.Half, 3)
205
+ assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3)
206
+
207
+
208
+ def test_factor_cache():
209
+ factor_cache.cache_clear()
210
+ raises(ValueError, lambda: factor_cache.__setitem__(1, 5))
211
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 1))
212
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 10))
213
+ raises(ValueError, lambda: factor_cache.__setitem__(10, 3))
214
+ raises(ValueError, lambda: factor_cache.__setitem__(20, 4))
215
+ factor_cache.maxsize = 3
216
+ for i in range(2, 10):
217
+ factor_cache[5*i] = 5
218
+ assert len(factor_cache) == 3
219
+ factor_cache.maxsize = 5
220
+ for i in range(2, 10):
221
+ factor_cache[5*i] = 5
222
+ assert len(factor_cache) == 5
223
+ factor_cache.maxsize = 2
224
+ assert len(factor_cache) == 2
225
+ factor_cache.maxsize =1000
226
+
227
+ factor_cache.cache_clear()
228
+ factor_cache[40] = 5
229
+ assert factor_cache.get(40) == 5
230
+ assert factor_cache.get(20) is None
231
+ assert factor_cache[40] == 5
232
+ raises(KeyError, lambda: factor_cache[10])
233
+ del factor_cache[40]
234
+ assert len(factor_cache) == 0
235
+ raises(KeyError, lambda: factor_cache.__delitem__(40))
236
+ factor_cache.add(100, [5, 2])
237
+ assert len(factor_cache) == 2
238
+ assert factor_cache[100] == 5
239
+
240
+ for n in [1000000007, 10000019*20000003]:
241
+ factorint(n)
242
+ assert n in factor_cache
243
+
244
+ # Restore the initial state
245
+ factor_cache.cache_clear()
246
+ factor_cache.maxsize = 1000
247
+
248
+
249
+ @slow
250
+ def test_factorint():
251
+ assert primefactors(123456) == [2, 3, 643]
252
+ assert factorint(0) == {0: 1}
253
+ assert factorint(1) == {}
254
+ assert factorint(-1) == {-1: 1}
255
+ assert factorint(-2) == {-1: 1, 2: 1}
256
+ assert factorint(-16) == {-1: 1, 2: 4}
257
+ assert factorint(2) == {2: 1}
258
+ assert factorint(126) == {2: 1, 3: 2, 7: 1}
259
+ assert factorint(123456) == {2: 6, 3: 1, 643: 1}
260
+ assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
261
+ assert factorint(64015937) == {7993: 1, 8009: 1}
262
+ assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
263
+ #issue 19683
264
+ assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
265
+ #issue 17676
266
+ assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
267
+ assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
268
+ assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}
269
+
270
+ assert factorint(0, multiple=True) == [0]
271
+ assert factorint(1, multiple=True) == []
272
+ assert factorint(-1, multiple=True) == [-1]
273
+ assert factorint(-2, multiple=True) == [-1, 2]
274
+ assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
275
+ assert factorint(2, multiple=True) == [2]
276
+ assert factorint(24, multiple=True) == [2, 2, 2, 3]
277
+ assert factorint(126, multiple=True) == [2, 3, 3, 7]
278
+ assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
279
+ assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
280
+ assert factorint(64015937, multiple=True) == [7993, 8009]
281
+ assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
282
+
283
+ assert factorint(fac(1, evaluate=False)) == {}
284
+ assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
285
+ assert factorint(fac(15, evaluate=False)) == \
286
+ {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
287
+ assert factorint(fac(20, evaluate=False)) == \
288
+ {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
289
+ assert factorint(fac(23, evaluate=False)) == \
290
+ {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}
291
+
292
+ assert multiproduct(factorint(fac(200))) == fac(200)
293
+ assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
294
+ for b, e in factorint(fac(150)).items():
295
+ assert e == fac_multiplicity(150, b)
296
+ for b, e in factorint(fac(150, evaluate=False)).items():
297
+ assert e == fac_multiplicity(150, b)
298
+ assert factorint(103005006059**7) == {103005006059: 7}
299
+ assert factorint(31337**191) == {31337: 191}
300
+ assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
301
+ {2: 1000, 3: 500, 257: 127, 383: 60}
302
+ assert len(factorint(fac(10000))) == 1229
303
+ assert len(factorint(fac(10000, evaluate=False))) == 1229
304
+ assert factorint(12932983746293756928584532764589230) == \
305
+ {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
306
+ assert factorint(727719592270351) == {727719592270351: 1}
307
+ assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
308
+ for n in range(60000):
309
+ assert multiproduct(factorint(n)) == n
310
+ assert pollard_rho(2**64 + 1, seed=1) == 274177
311
+ assert pollard_rho(19, seed=1) is None
312
+ assert factorint(3, limit=2) == {3: 1}
313
+ assert factorint(12345) == {3: 1, 5: 1, 823: 1}
314
+ assert factorint(
315
+ 12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit
316
+ assert factorint(1, limit=1) == {}
317
+ assert factorint(0, 3) == {0: 1}
318
+ assert factorint(12, limit=1) == {12: 1}
319
+ assert factorint(30, limit=2) == {2: 1, 15: 1}
320
+ assert factorint(16, limit=2) == {2: 4}
321
+ assert factorint(124, limit=3) == {2: 2, 31: 1}
322
+ assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
323
+ p1 = nextprime(2**32)
324
+ p2 = nextprime(2**16)
325
+ p3 = nextprime(p2)
326
+ assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
327
+ assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
328
+ assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
329
+ assert factorint(primorial(17) + 1, use_pm1=0) == \
330
+ {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
331
+ # when prime b is closer than approx sqrt(8*p) to prime p then they are
332
+ # "close" and have a trivial factorization
333
+ a = nextprime(2**2**8) # 78 digits
334
+ b = nextprime(a + 2**2**4)
335
+ assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
336
+
337
+ raises(ValueError, lambda: pollard_rho(4))
338
+ raises(ValueError, lambda: pollard_pm1(3))
339
+ raises(ValueError, lambda: pollard_pm1(10, B=2))
340
+ # verbose coverage
341
+ n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
342
+ assert 'with primes' in capture(lambda: factorint(n, verbose=1))
343
+ capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
344
+
345
+ n = nextprime(2**17)
346
+ capture(lambda: factorint(n**3, verbose=1)) # perfect power termination
347
+ capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg
348
+
349
+ # exceed 1st
350
+ n = nextprime(2**17)
351
+ n *= nextprime(n)
352
+ assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
353
+ n *= nextprime(n)
354
+ assert len(factorint(n)) == 3
355
+ assert len(factorint(n, limit=p1)) == 3
356
+ n *= nextprime(2*n)
357
+ # exceed 2nd
358
+ assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
359
+ assert capture(
360
+ lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
361
+ # non-prime pm1 result
362
+ n = nextprime(8069)
363
+ n *= nextprime(2*n)*nextprime(2*n, 2)
364
+ capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result
365
+ # factor fermat composite
366
+ p1 = nextprime(2**17)
367
+ p2 = nextprime(2*p1)
368
+ assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
369
+ # Test for non integer input
370
+ raises(ValueError, lambda: factorint(4.5))
371
+ # test dict/Dict input
372
+ sans = '2**10*3**3'
373
+ n = {4: 2, 12: 3}
374
+ assert str(factorint(n)) == sans
375
+ assert str(factorint(Dict(n))) == sans
376
+
377
+
378
+ def test_divisors_and_divisor_count():
379
+ assert divisors(-1) == [1]
380
+ assert divisors(0) == []
381
+ assert divisors(1) == [1]
382
+ assert divisors(2) == [1, 2]
383
+ assert divisors(3) == [1, 3]
384
+ assert divisors(17) == [1, 17]
385
+ assert divisors(10) == [1, 2, 5, 10]
386
+ assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
387
+ assert divisors(101) == [1, 101]
388
+ assert type(divisors(2, generator=True)) is not list
389
+
390
+ assert divisor_count(0) == 0
391
+ assert divisor_count(-1) == 1
392
+ assert divisor_count(1) == 1
393
+ assert divisor_count(6) == 4
394
+ assert divisor_count(12) == 6
395
+
396
+ assert divisor_count(180, 3) == divisor_count(180//3)
397
+ assert divisor_count(2*3*5, 7) == 0
398
+
399
+
400
+ def test_proper_divisors_and_proper_divisor_count():
401
+ assert proper_divisors(-1) == []
402
+ assert proper_divisors(0) == []
403
+ assert proper_divisors(1) == []
404
+ assert proper_divisors(2) == [1]
405
+ assert proper_divisors(3) == [1]
406
+ assert proper_divisors(17) == [1]
407
+ assert proper_divisors(10) == [1, 2, 5]
408
+ assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50]
409
+ assert proper_divisors(1000000007) == [1]
410
+ assert type(proper_divisors(2, generator=True)) is not list
411
+
412
+ assert proper_divisor_count(0) == 0
413
+ assert proper_divisor_count(-1) == 0
414
+ assert proper_divisor_count(1) == 0
415
+ assert proper_divisor_count(36) == 8
416
+ assert proper_divisor_count(2*3*5) == 7
417
+
418
+
419
+ def test_udivisors_and_udivisor_count():
420
+ assert udivisors(-1) == [1]
421
+ assert udivisors(0) == []
422
+ assert udivisors(1) == [1]
423
+ assert udivisors(2) == [1, 2]
424
+ assert udivisors(3) == [1, 3]
425
+ assert udivisors(17) == [1, 17]
426
+ assert udivisors(10) == [1, 2, 5, 10]
427
+ assert udivisors(100) == [1, 4, 25, 100]
428
+ assert udivisors(101) == [1, 101]
429
+ assert udivisors(1000) == [1, 8, 125, 1000]
430
+ assert type(udivisors(2, generator=True)) is not list
431
+
432
+ assert udivisor_count(0) == 0
433
+ assert udivisor_count(-1) == 1
434
+ assert udivisor_count(1) == 1
435
+ assert udivisor_count(6) == 4
436
+ assert udivisor_count(12) == 4
437
+
438
+ assert udivisor_count(180) == 8
439
+ assert udivisor_count(2*3*5*7) == 16
440
+
441
+
442
+ def test_issue_6981():
443
+ S = set(divisors(4)).union(set(divisors(Integer(2))))
444
+ assert S == {1,2,4}
445
+
446
+
447
+ def test_issue_4356():
448
+ assert factorint(1030903) == {53: 2, 367: 1}
449
+
450
+
451
+ def test_divisors():
452
+ assert divisors(28) == [1, 2, 4, 7, 14, 28]
453
+ assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105]
454
+ assert divisors(0) == []
455
+
456
+
457
+ def test_divisor_count():
458
+ assert divisor_count(0) == 0
459
+ assert divisor_count(6) == 4
460
+
461
+
462
+ def test_proper_divisors():
463
+ assert proper_divisors(-1) == []
464
+ assert proper_divisors(28) == [1, 2, 4, 7, 14]
465
+ assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35]
466
+
467
+
468
+ def test_proper_divisor_count():
469
+ assert proper_divisor_count(6) == 3
470
+ assert proper_divisor_count(108) == 11
471
+
472
+
473
+ def test_antidivisors():
474
+ assert antidivisors(-1) == []
475
+ assert antidivisors(-3) == [2]
476
+ assert antidivisors(14) == [3, 4, 9]
477
+ assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
478
+ assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
479
+ assert antidivisors(393216) == [262144]
480
+ assert sorted(x for x in antidivisors(3*5*7, 1)) == \
481
+ [2, 6, 10, 11, 14, 19, 30, 42, 70]
482
+ assert antidivisors(1) == []
483
+ assert type(antidivisors(2, generator=True)) is not list
484
+
485
+ def test_antidivisor_count():
486
+ assert antidivisor_count(0) == 0
487
+ assert antidivisor_count(-1) == 0
488
+ assert antidivisor_count(-4) == 1
489
+ assert antidivisor_count(20) == 3
490
+ assert antidivisor_count(25) == 5
491
+ assert antidivisor_count(38) == 7
492
+ assert antidivisor_count(180) == 6
493
+ assert antidivisor_count(2*3*5) == 3
494
+
495
+
496
+ def test_smoothness_and_smoothness_p():
497
+ assert smoothness(1) == (1, 1)
498
+ assert smoothness(2**4*3**2) == (3, 16)
499
+
500
+ assert smoothness_p(10431, m=1) == \
501
+ (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
502
+ assert smoothness_p(10431) == \
503
+ (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
504
+ assert smoothness_p(10431, power=1) == \
505
+ (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
506
+ assert smoothness_p(21477639576571, visual=1) == \
507
+ 'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
508
+ 'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
509
+
510
+
511
+ def test_visual_factorint():
512
+ assert factorint(1, visual=1) == 1
513
+ forty2 = factorint(42, visual=True)
514
+ assert type(forty2) == Mul
515
+ assert str(forty2) == '2**1*3**1*7**1'
516
+ assert factorint(1, visual=True) is S.One
517
+ no = {"evaluate": False}
518
+ assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
519
+ Pow(3, 2, **no),
520
+ Pow(7, 2, **no), **no)
521
+ assert -1 in factorint(-42, visual=True).args
522
+
523
+
524
+ def test_factorrat():
525
+ assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
526
+ assert str(factorrat(Rational(1, 1), visual=True)) == '1'
527
+ assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
528
+ assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)'
529
+ assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)'
530
+
531
+ assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
532
+ assert factorrat(Rational(1, 1), multiple=True) == []
533
+ assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5]
534
+ assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5]
535
+ assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3]
536
+ assert factorrat(S(-25)/14/9, multiple=True) == \
537
+ [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5]
538
+
539
+
540
+ def test_visual_io():
541
+ sm = smoothness_p
542
+ fi = factorint
543
+ # with smoothness_p
544
+ n = 124
545
+ d = fi(n)
546
+ m = fi(d, visual=True)
547
+ t = sm(n)
548
+ s = sm(t)
549
+ for th in [d, s, t, n, m]:
550
+ assert sm(th, visual=True) == s
551
+ assert sm(th, visual=1) == s
552
+ for th in [d, s, t, n, m]:
553
+ assert sm(th, visual=False) == t
554
+ assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
555
+ assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
556
+
557
+ # with factorint
558
+ for th in [d, m, n]:
559
+ assert fi(th, visual=True) == m
560
+ assert fi(th, visual=1) == m
561
+ for th in [d, m, n]:
562
+ assert fi(th, visual=False) == d
563
+ assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
564
+ assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
565
+
566
+ # test reevaluation
567
+ no = {"evaluate": False}
568
+ assert sm({4: 2}, visual=False) == sm(16)
569
+ assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
570
+ visual=False) == sm(2**10)
571
+
572
+ assert fi({4: 2}, visual=False) == fi(16)
573
+ assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
574
+ visual=False) == fi(2**10)
575
+
576
+
577
+ def test_core():
578
+ assert core(35**13, 10) == 42875
579
+ assert core(210**2) == 1
580
+ assert core(7776, 3) == 36
581
+ assert core(10**27, 22) == 10**5
582
+ assert core(537824) == 14
583
+ assert core(1, 6) == 1
584
+
585
+
586
+ def test__divisor_sigma():
587
+ assert _divisor_sigma(23450) == 50592
588
+ assert _divisor_sigma(23450, 0) == 24
589
+ assert _divisor_sigma(23450, 1) == 50592
590
+ assert _divisor_sigma(23450, 2) == 730747500
591
+ assert _divisor_sigma(23450, 3) == 14666785333344
592
+ A000005 = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6, 4,
593
+ 4, 2, 8, 3, 4, 4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4, 8, 2, 8]
594
+ for n, val in enumerate(A000005, 1):
595
+ assert _divisor_sigma(n, 0) == val
596
+ A000203 = [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12, 28, 14, 24, 24, 31, 18,
597
+ 39, 20, 42, 32, 36, 24, 60, 31, 42, 40, 56, 30, 72, 32, 63, 48]
598
+ for n, val in enumerate(A000203, 1):
599
+ assert _divisor_sigma(n, 1) == val
600
+ A001157 = [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122, 210, 170, 250, 260,
601
+ 341, 290, 455, 362, 546, 500, 610, 530, 850, 651, 850, 820, 1050]
602
+ for n, val in enumerate(A001157, 1):
603
+ assert _divisor_sigma(n, 2) == val
604
+
605
+
606
+ def test_mersenne_prime_exponent():
607
+ assert mersenne_prime_exponent(1) == 2
608
+ assert mersenne_prime_exponent(4) == 7
609
+ assert mersenne_prime_exponent(10) == 89
610
+ assert mersenne_prime_exponent(25) == 21701
611
+ raises(ValueError, lambda: mersenne_prime_exponent(52))
612
+ raises(ValueError, lambda: mersenne_prime_exponent(0))
613
+
614
+
615
+ def test_is_perfect():
616
+ assert is_perfect(-6) is False
617
+ assert is_perfect(6) is True
618
+ assert is_perfect(15) is False
619
+ assert is_perfect(28) is True
620
+ assert is_perfect(400) is False
621
+ assert is_perfect(496) is True
622
+ assert is_perfect(8128) is True
623
+ assert is_perfect(10000) is False
624
+
625
+
626
+ def test_is_abundant():
627
+ assert is_abundant(10) is False
628
+ assert is_abundant(12) is True
629
+ assert is_abundant(18) is True
630
+ assert is_abundant(21) is False
631
+ assert is_abundant(945) is True
632
+
633
+
634
+ def test_is_deficient():
635
+ assert is_deficient(10) is True
636
+ assert is_deficient(22) is True
637
+ assert is_deficient(56) is False
638
+ assert is_deficient(20) is False
639
+ assert is_deficient(36) is False
640
+
641
+
642
+ def test_is_amicable():
643
+ assert is_amicable(173, 129) is False
644
+ assert is_amicable(220, 284) is True
645
+ assert is_amicable(8756, 8756) is False
646
+
647
+
648
+ def test_is_carmichael():
649
+ A002997 = [561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841,
650
+ 29341, 41041, 46657, 52633, 62745, 63973, 75361, 101101]
651
+ for n in range(1, 5000):
652
+ assert is_carmichael(n) == (n in A002997)
653
+ for n in A002997:
654
+ assert is_carmichael(n)
655
+
656
+
657
+ def test_find_carmichael_numbers_in_range():
658
+ assert find_carmichael_numbers_in_range(0, 561) == []
659
+ assert find_carmichael_numbers_in_range(561, 562) == [561]
660
+ assert find_carmichael_numbers_in_range(561, 1105) == find_carmichael_numbers_in_range(561, 562)
661
+ raises(ValueError, lambda: find_carmichael_numbers_in_range(-2, 2))
662
+ raises(ValueError, lambda: find_carmichael_numbers_in_range(22, 2))
663
+
664
+
665
+ def test_find_first_n_carmichaels():
666
+ assert find_first_n_carmichaels(0) == []
667
+ assert find_first_n_carmichaels(1) == [561]
668
+ assert find_first_n_carmichaels(2) == [561, 1105]
669
+
670
+
671
+ def test_dra():
672
+ assert dra(19, 12) == 8
673
+ assert dra(2718, 10) == 9
674
+ assert dra(0, 22) == 0
675
+ assert dra(23456789, 10) == 8
676
+ raises(ValueError, lambda: dra(24, -2))
677
+ raises(ValueError, lambda: dra(24.2, 5))
678
+
679
+ def test_drm():
680
+ assert drm(19, 12) == 7
681
+ assert drm(2718, 10) == 2
682
+ assert drm(0, 15) == 0
683
+ assert drm(234161, 10) == 6
684
+ raises(ValueError, lambda: drm(24, -2))
685
+ raises(ValueError, lambda: drm(11.6, 9))
686
+
687
+
688
+ def test_deprecated_ntheory_symbolic_functions():
689
+ from sympy.testing.pytest import warns_deprecated_sympy
690
+
691
+ with warns_deprecated_sympy():
692
+ assert primenu(3) == 1
693
+ with warns_deprecated_sympy():
694
+ assert primeomega(3) == 1
695
+ with warns_deprecated_sympy():
696
+ assert totient(3) == 2
697
+ with warns_deprecated_sympy():
698
+ assert reduced_totient(3) == 2
699
+ with warns_deprecated_sympy():
700
+ assert divisor_sigma(3) == 4
701
+ with warns_deprecated_sympy():
702
+ assert udivisor_sigma(3) == 4
.venv/Lib/site-packages/sympy/ntheory/tests/test_generate.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from bisect import bisect, bisect_left
2
+
3
+ from sympy.functions.combinatorial.numbers import mobius, totient
4
+ from sympy.ntheory.generate import (sieve, Sieve)
5
+
6
+ from sympy.ntheory import isprime, randprime, nextprime, prevprime, \
7
+ primerange, primepi, prime, primorial, composite, compositepi
8
+ from sympy.ntheory.generate import cycle_length, _primepi
9
+ from sympy.ntheory.primetest import mr
10
+ from sympy.testing.pytest import raises
11
+
12
+ def test_prime():
13
+ assert prime(1) == 2
14
+ assert prime(2) == 3
15
+ assert prime(5) == 11
16
+ assert prime(11) == 31
17
+ assert prime(57) == 269
18
+ assert prime(296) == 1949
19
+ assert prime(559) == 4051
20
+ assert prime(3000) == 27449
21
+ assert prime(4096) == 38873
22
+ assert prime(9096) == 94321
23
+ assert prime(25023) == 287341
24
+ assert prime(10000000) == 179424673 # issue #20951
25
+ assert prime(99999999) == 2038074739
26
+ raises(ValueError, lambda: prime(0))
27
+ sieve.extend(3000)
28
+ assert prime(401) == 2749
29
+ raises(ValueError, lambda: prime(-1))
30
+
31
+
32
+ def test__primepi():
33
+ assert _primepi(-1) == 0
34
+ assert _primepi(1) == 0
35
+ assert _primepi(2) == 1
36
+ assert _primepi(5) == 3
37
+ assert _primepi(11) == 5
38
+ assert _primepi(57) == 16
39
+ assert _primepi(296) == 62
40
+ assert _primepi(559) == 102
41
+ assert _primepi(3000) == 430
42
+ assert _primepi(4096) == 564
43
+ assert _primepi(9096) == 1128
44
+ assert _primepi(25023) == 2763
45
+ assert _primepi(10**8) == 5761455
46
+ assert _primepi(253425253) == 13856396
47
+ assert _primepi(8769575643) == 401464322
48
+ sieve.extend(3000)
49
+ assert _primepi(2000) == 303
50
+
51
+
52
+ def test_composite():
53
+ from sympy.ntheory.generate import sieve
54
+ sieve._reset()
55
+ assert composite(1) == 4
56
+ assert composite(2) == 6
57
+ assert composite(5) == 10
58
+ assert composite(11) == 20
59
+ assert composite(41) == 58
60
+ assert composite(57) == 80
61
+ assert composite(296) == 370
62
+ assert composite(559) == 684
63
+ assert composite(3000) == 3488
64
+ assert composite(4096) == 4736
65
+ assert composite(9096) == 10368
66
+ assert composite(25023) == 28088
67
+ sieve.extend(3000)
68
+ assert composite(1957) == 2300
69
+ assert composite(2568) == 2998
70
+ raises(ValueError, lambda: composite(0))
71
+
72
+
73
+ def test_compositepi():
74
+ assert compositepi(1) == 0
75
+ assert compositepi(2) == 0
76
+ assert compositepi(5) == 1
77
+ assert compositepi(11) == 5
78
+ assert compositepi(57) == 40
79
+ assert compositepi(296) == 233
80
+ assert compositepi(559) == 456
81
+ assert compositepi(3000) == 2569
82
+ assert compositepi(4096) == 3531
83
+ assert compositepi(9096) == 7967
84
+ assert compositepi(25023) == 22259
85
+ assert compositepi(10**8) == 94238544
86
+ assert compositepi(253425253) == 239568856
87
+ assert compositepi(8769575643) == 8368111320
88
+ sieve.extend(3000)
89
+ assert compositepi(2321) == 1976
90
+
91
+
92
+ def test_generate():
93
+ from sympy.ntheory.generate import sieve
94
+ sieve._reset()
95
+ assert nextprime(-4) == 2
96
+ assert nextprime(2) == 3
97
+ assert nextprime(5) == 7
98
+ assert nextprime(12) == 13
99
+ assert prevprime(3) == 2
100
+ assert prevprime(7) == 5
101
+ assert prevprime(13) == 11
102
+ assert prevprime(19) == 17
103
+ assert prevprime(20) == 19
104
+
105
+ sieve.extend_to_no(9)
106
+ assert sieve._list[-1] == 23
107
+
108
+ assert sieve._list[-1] < 31
109
+ assert 31 in sieve
110
+
111
+ assert nextprime(90) == 97
112
+ assert nextprime(10**40) == (10**40 + 121)
113
+ primelist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
114
+ 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
115
+ 79, 83, 89, 97, 101, 103, 107, 109, 113,
116
+ 127, 131, 137, 139, 149, 151, 157, 163,
117
+ 167, 173, 179, 181, 191, 193, 197, 199,
118
+ 211, 223, 227, 229, 233, 239, 241, 251,
119
+ 257, 263, 269, 271, 277, 281, 283, 293]
120
+ for i in range(len(primelist) - 2):
121
+ for j in range(2, len(primelist) - i):
122
+ assert nextprime(primelist[i], j) == primelist[i + j]
123
+ if 3 < i:
124
+ assert nextprime(primelist[i] - 1, j) == primelist[i + j - 1]
125
+ raises(ValueError, lambda: nextprime(2, 0))
126
+ raises(ValueError, lambda: nextprime(2, -1))
127
+ assert prevprime(97) == 89
128
+ assert prevprime(10**40) == (10**40 - 17)
129
+
130
+ raises(ValueError, lambda: Sieve(0))
131
+ raises(ValueError, lambda: Sieve(-1))
132
+ for sieve_interval in [1, 10, 11, 1_000_000]:
133
+ s = Sieve(sieve_interval=sieve_interval)
134
+ for head in range(s._list[-1] + 1, (s._list[-1] + 1)**2, 2):
135
+ for tail in range(head + 1, (s._list[-1] + 1)**2):
136
+ A = list(s._primerange(head, tail))
137
+ B = primelist[bisect(primelist, head):bisect_left(primelist, tail)]
138
+ assert A == B
139
+ for k in range(s._list[-1], primelist[-1] - 1, 2):
140
+ s = Sieve(sieve_interval=sieve_interval)
141
+ s.extend(k)
142
+ assert list(s._list) == primelist[:bisect(primelist, k)]
143
+ s.extend(primelist[-1])
144
+ assert list(s._list) == primelist
145
+
146
+ assert list(sieve.primerange(10, 1)) == []
147
+ assert list(sieve.primerange(5, 9)) == [5, 7]
148
+ sieve._reset(prime=True)
149
+ assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
150
+ assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
151
+ assert list(sieve.primerange(8)) == [2, 3, 5, 7]
152
+ assert list(sieve.primerange(-2)) == []
153
+ assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
154
+ assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
155
+
156
+ assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
157
+ sieve._reset(totient=True)
158
+ assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
159
+ assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
160
+ assert list(sieve.totientrange(0, 1)) == []
161
+ assert list(sieve.totientrange(1, 2)) == [1]
162
+
163
+ assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
164
+ sieve._reset(mobius=True)
165
+ assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
166
+ assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
167
+ assert list(sieve.mobiusrange(0, 1)) == []
168
+ assert list(sieve.mobiusrange(1, 2)) == [1]
169
+
170
+ assert list(primerange(10, 1)) == []
171
+ assert list(primerange(2, 7)) == [2, 3, 5]
172
+ assert list(primerange(2, 10)) == [2, 3, 5, 7]
173
+ assert list(primerange(1050, 1100)) == [1051, 1061,
174
+ 1063, 1069, 1087, 1091, 1093, 1097]
175
+ s = Sieve()
176
+ for i in range(30, 2350, 376):
177
+ for j in range(2, 5096, 1139):
178
+ A = list(s.primerange(i, i + j))
179
+ B = list(primerange(i, i + j))
180
+ assert A == B
181
+ s = Sieve()
182
+ sieve._reset(prime=True)
183
+ sieve.extend(13)
184
+ for i in range(200):
185
+ for j in range(i, 200):
186
+ A = list(s.primerange(i, j))
187
+ B = list(primerange(i, j))
188
+ assert A == B
189
+ sieve.extend(1000)
190
+ for a, b in [(901, 1103), # a < 1000 < b < 1000**2
191
+ (806, 1002007), # a < 1000 < 1000**2 < b
192
+ (2000, 30001), # 1000 < a < b < 1000**2
193
+ (100005, 1010001), # 1000 < a < 1000**2 < b
194
+ (1003003, 1005000), # 1000**2 < a < b
195
+ ]:
196
+ assert list(primerange(a, b)) == list(s.primerange(a, b))
197
+ sieve._reset(prime=True)
198
+ sieve.extend(100000)
199
+ assert len(sieve._list) == len(set(sieve._list))
200
+ s = Sieve()
201
+ assert s[10] == 29
202
+
203
+ assert nextprime(2, 2) == 5
204
+
205
+ raises(ValueError, lambda: totient(0))
206
+
207
+ raises(ValueError, lambda: primorial(0))
208
+
209
+ assert mr(1, [2]) is False
210
+
211
+ func = lambda i: (i**2 + 1) % 51
212
+ assert next(cycle_length(func, 4)) == (6, 3)
213
+ assert list(cycle_length(func, 4, values=True)) == \
214
+ [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
215
+ assert next(cycle_length(func, 4, nmax=5)) == (5, None)
216
+ assert list(cycle_length(func, 4, nmax=5, values=True)) == \
217
+ [4, 17, 35, 2, 5]
218
+ sieve.extend(3000)
219
+ assert nextprime(2968) == 2969
220
+ assert prevprime(2930) == 2927
221
+ raises(ValueError, lambda: prevprime(1))
222
+ raises(ValueError, lambda: prevprime(-4))
223
+
224
+
225
+ def test_randprime():
226
+ assert randprime(10, 1) is None
227
+ assert randprime(3, -3) is None
228
+ assert randprime(2, 3) == 2
229
+ assert randprime(1, 3) == 2
230
+ assert randprime(3, 5) == 3
231
+ raises(ValueError, lambda: randprime(-12, -2))
232
+ raises(ValueError, lambda: randprime(-10, 0))
233
+ raises(ValueError, lambda: randprime(20, 22))
234
+ raises(ValueError, lambda: randprime(0, 2))
235
+ raises(ValueError, lambda: randprime(1, 2))
236
+ for a in [100, 300, 500, 250000]:
237
+ for b in [100, 300, 500, 250000]:
238
+ p = randprime(a, a + b)
239
+ assert a <= p < (a + b) and isprime(p)
240
+
241
+
242
+ def test_primorial():
243
+ assert primorial(1) == 2
244
+ assert primorial(1, nth=0) == 1
245
+ assert primorial(2) == 6
246
+ assert primorial(2, nth=0) == 2
247
+ assert primorial(4, nth=0) == 6
248
+
249
+
250
+ def test_search():
251
+ assert 2 in sieve
252
+ assert 2.1 not in sieve
253
+ assert 1 not in sieve
254
+ assert 2**1000 not in sieve
255
+ raises(ValueError, lambda: sieve.search(1))
256
+
257
+
258
+ def test_sieve_slice():
259
+ assert sieve[5] == 11
260
+ assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
261
+ assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
262
+ assert list(sieve[1:5]) == [2, 3, 5, 7]
263
+ raises(IndexError, lambda: sieve[:5])
264
+ raises(IndexError, lambda: sieve[0])
265
+ raises(IndexError, lambda: sieve[0:5])
266
+
267
+ def test_sieve_iter():
268
+ values = []
269
+ for value in sieve:
270
+ if value > 7:
271
+ break
272
+ values.append(value)
273
+ assert values == list(sieve[1:5])
274
+
275
+
276
+ def test_sieve_repr():
277
+ assert "sieve" in repr(sieve)
278
+ assert "prime" in repr(sieve)
279
+
280
+
281
+ def test_deprecated_ntheory_symbolic_functions():
282
+ from sympy.testing.pytest import warns_deprecated_sympy
283
+
284
+ with warns_deprecated_sympy():
285
+ assert primepi(0) == 0
.venv/Lib/site-packages/sympy/ntheory/tests/test_hypothesis.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hypothesis import given
2
+ from hypothesis import strategies as st
3
+ from sympy import divisors
4
+ from sympy.functions.combinatorial.numbers import divisor_sigma, totient
5
+ from sympy.ntheory.primetest import is_square
6
+
7
+
8
+ @given(n=st.integers(1, 10**10))
9
+ def test_tau_hypothesis(n):
10
+ div = divisors(n)
11
+ tau_n = len(div)
12
+ assert is_square(n) == (tau_n % 2 == 1)
13
+ sigmas = [divisor_sigma(i) for i in div]
14
+ totients = [totient(n // i) for i in div]
15
+ mul = [a * b for a, b in zip(sigmas, totients)]
16
+ assert n * tau_n == sum(mul)
17
+
18
+
19
+ @given(n=st.integers(1, 10**10))
20
+ def test_totient_hypothesis(n):
21
+ assert totient(n) <= n
22
+ div = divisors(n)
23
+ totients = [totient(i) for i in div]
24
+ assert n == sum(totients)
.venv/Lib/site-packages/sympy/ntheory/tests/test_modular.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
2
+ from sympy.testing.pytest import raises
3
+
4
+
5
+ def test_crt():
6
+ def mcrt(m, v, r, symmetric=False):
7
+ assert crt(m, v, symmetric)[0] == r
8
+ mm, e, s = crt1(m)
9
+ assert crt2(m, v, mm, e, s, symmetric) == (r, mm)
10
+
11
+ mcrt([2, 3, 5], [0, 0, 0], 0)
12
+ mcrt([2, 3, 5], [1, 1, 1], 1)
13
+
14
+ mcrt([2, 3, 5], [-1, -1, -1], -1, True)
15
+ mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False)
16
+
17
+ assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800)
18
+
19
+
20
+ def test_modular():
21
+ assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140)
22
+ assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None
23
+ assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547)
24
+ assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547)
25
+ assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None
26
+ assert solve_congruence(
27
+ *list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547)
28
+ assert solve_congruence(
29
+ *list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
30
+ assert solve_congruence(
31
+ *list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
32
+ assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None
33
+ raises(
34
+ ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17]))))
.venv/Lib/site-packages/sympy/ntheory/tests/test_multinomial.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients)
2
+ from sympy.ntheory.multinomial import multinomial_coefficients_iterator
3
+
4
+
5
+ def test_binomial_coefficients_list():
6
+ assert binomial_coefficients_list(0) == [1]
7
+ assert binomial_coefficients_list(1) == [1, 1]
8
+ assert binomial_coefficients_list(2) == [1, 2, 1]
9
+ assert binomial_coefficients_list(3) == [1, 3, 3, 1]
10
+ assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1]
11
+ assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1]
12
+ assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1]
13
+
14
+
15
+ def test_binomial_coefficients():
16
+ for n in range(15):
17
+ c = binomial_coefficients(n)
18
+ l = [c[k] for k in sorted(c)]
19
+ assert l == binomial_coefficients_list(n)
20
+
21
+
22
+ def test_multinomial_coefficients():
23
+ assert multinomial_coefficients(1, 1) == {(1,): 1}
24
+ assert multinomial_coefficients(1, 2) == {(2,): 1}
25
+ assert multinomial_coefficients(1, 3) == {(3,): 1}
26
+ assert multinomial_coefficients(2, 0) == {(0, 0): 1}
27
+ assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1}
28
+ assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2}
29
+ assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1,
30
+ (2, 1): 3}
31
+ assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1,
32
+ (0, 0, 1): 1}
33
+ assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1,
34
+ (1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1}
35
+ mc = multinomial_coefficients(3, 3)
36
+ assert mc == {(2, 1, 0): 3, (0, 3, 0): 1,
37
+ (1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1,
38
+ (2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1}
39
+ assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1}
40
+ assert dict(
41
+ multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1}
42
+ assert dict(multinomial_coefficients_iterator(2, 2)) == \
43
+ {(2, 0): 1, (0, 2): 1, (1, 1): 2}
44
+ assert dict(multinomial_coefficients_iterator(3, 3)) == mc
45
+ it = multinomial_coefficients_iterator(7, 2)
46
+ assert [next(it) for i in range(4)] == \
47
+ [((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2),
48
+ ((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)]
.venv/Lib/site-packages/sympy/ntheory/tests/test_partitions.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.partitions_ import npartitions, _partition_rec, _partition
2
+
3
+
4
+ def test__partition_rec():
5
+ A000041 = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135,
6
+ 176, 231, 297, 385, 490, 627, 792, 1002, 1255, 1575]
7
+ for n, val in enumerate(A000041):
8
+ assert _partition_rec(n) == val
9
+
10
+
11
+ def test__partition():
12
+ assert [_partition(k) for k in range(13)] == \
13
+ [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77]
14
+ assert _partition(100) == 190569292
15
+ assert _partition(200) == 3972999029388
16
+ assert _partition(1000) == 24061467864032622473692149727991
17
+ assert _partition(1001) == 25032297938763929621013218349796
18
+ assert _partition(2000) == 4720819175619413888601432406799959512200344166
19
+ assert _partition(10000) % 10**10 == 6916435144
20
+ assert _partition(100000) % 10**10 == 9421098519
21
+ assert _partition(10000000) % 10**10 == 7677288980
22
+
23
+
24
+ def test_deprecated_ntheory_symbolic_functions():
25
+ from sympy.testing.pytest import warns_deprecated_sympy
26
+
27
+ with warns_deprecated_sympy():
28
+ assert npartitions(0) == 1
.venv/Lib/site-packages/sympy/ntheory/tests/test_primetest.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import gcd
2
+
3
+ from sympy.ntheory.generate import Sieve, sieve
4
+ from sympy.ntheory.primetest import (mr, _lucas_extrastrong_params, is_lucas_prp, is_square,
5
+ is_strong_lucas_prp, is_extra_strong_lucas_prp,
6
+ proth_test, isprime, is_euler_pseudoprime,
7
+ is_gaussian_prime, is_fermat_pseudoprime, is_euler_jacobi_pseudoprime,
8
+ MERSENNE_PRIME_EXPONENTS, _lucas_lehmer_primality_test,
9
+ is_mersenne_prime)
10
+
11
+ from sympy.testing.pytest import slow, raises
12
+ from sympy.core.numbers import I, Float
13
+
14
+
15
+ def test_is_fermat_pseudoprime():
16
+ assert is_fermat_pseudoprime(5, 1)
17
+ assert is_fermat_pseudoprime(9, 1)
18
+
19
+
20
+ def test_euler_pseudoprimes():
21
+ assert is_euler_pseudoprime(13, 1)
22
+ assert is_euler_pseudoprime(15, 1)
23
+ assert is_euler_pseudoprime(17, 6)
24
+ assert is_euler_pseudoprime(101, 7)
25
+ assert is_euler_pseudoprime(1009, 10)
26
+ assert is_euler_pseudoprime(11287, 41)
27
+
28
+ raises(ValueError, lambda: is_euler_pseudoprime(0, 4))
29
+ raises(ValueError, lambda: is_euler_pseudoprime(3, 0))
30
+ raises(ValueError, lambda: is_euler_pseudoprime(15, 6))
31
+
32
+ # A006970
33
+ euler_prp = [341, 561, 1105, 1729, 1905, 2047, 2465, 3277,
34
+ 4033, 4681, 5461, 6601, 8321, 8481, 10261, 10585]
35
+ for p in euler_prp:
36
+ assert is_euler_pseudoprime(p, 2)
37
+
38
+ # A048950
39
+ euler_prp = [121, 703, 1729, 1891, 2821, 3281, 7381, 8401, 8911, 10585,
40
+ 12403, 15457, 15841, 16531, 18721, 19345, 23521, 24661, 28009]
41
+ for p in euler_prp:
42
+ assert is_euler_pseudoprime(p, 3)
43
+
44
+ # A033181
45
+ absolute_euler_prp = [1729, 2465, 15841, 41041, 46657, 75361,
46
+ 162401, 172081, 399001, 449065, 488881]
47
+ for p in absolute_euler_prp:
48
+ for a in range(2, p):
49
+ if gcd(a, p) != 1:
50
+ continue
51
+ assert is_euler_pseudoprime(p, a)
52
+
53
+
54
+ def test_is_euler_jacobi_pseudoprime():
55
+ assert is_euler_jacobi_pseudoprime(11, 1)
56
+ assert is_euler_jacobi_pseudoprime(15, 1)
57
+
58
+
59
+ def test_lucas_extrastrong_params():
60
+ assert _lucas_extrastrong_params(3) == (5, 3, 1)
61
+ assert _lucas_extrastrong_params(5) == (12, 4, 1)
62
+ assert _lucas_extrastrong_params(7) == (5, 3, 1)
63
+ assert _lucas_extrastrong_params(9) == (0, 0, 0)
64
+ assert _lucas_extrastrong_params(11) == (21, 5, 1)
65
+ assert _lucas_extrastrong_params(59) == (32, 6, 1)
66
+ assert _lucas_extrastrong_params(479) == (117, 11, 1)
67
+
68
+
69
+ def test_is_extra_strong_lucas_prp():
70
+ assert is_extra_strong_lucas_prp(4) == False
71
+ assert is_extra_strong_lucas_prp(989) == True
72
+ assert is_extra_strong_lucas_prp(10877) == True
73
+ assert is_extra_strong_lucas_prp(9) == False
74
+ assert is_extra_strong_lucas_prp(16) == False
75
+ assert is_extra_strong_lucas_prp(169) == False
76
+
77
+ @slow
78
+ def test_prps():
79
+ oddcomposites = [n for n in range(1, 10**5) if
80
+ n % 2 and not isprime(n)]
81
+ # A checksum would be better.
82
+ assert sum(oddcomposites) == 2045603465
83
+ assert [n for n in oddcomposites if mr(n, [2])] == [
84
+ 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141,
85
+ 52633, 65281, 74665, 80581, 85489, 88357, 90751]
86
+ assert [n for n in oddcomposites if mr(n, [3])] == [
87
+ 121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531,
88
+ 18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139,
89
+ 74593, 79003, 82513, 87913, 88573, 97567]
90
+ assert [n for n in oddcomposites if mr(n, [325])] == [
91
+ 9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059,
92
+ 2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911,
93
+ 12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649,
94
+ 24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041,
95
+ 55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641,
96
+ 76793, 78409, 85879]
97
+ assert not any(mr(n, [9345883071009581737]) for n in oddcomposites)
98
+ assert [n for n in oddcomposites if is_lucas_prp(n)] == [
99
+ 323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877,
100
+ 11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971,
101
+ 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323,
102
+ 32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099,
103
+ 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377,
104
+ 63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799,
105
+ 82983, 84419, 86063, 90287, 94667, 97019, 97439]
106
+ assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [
107
+ 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309,
108
+ 58519, 75077, 97439]
109
+ assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n)
110
+ ] == [
111
+ 989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059,
112
+ 72389, 73919, 75077]
113
+
114
+
115
+ def test_proth_test():
116
+ # Proth number
117
+ A080075 = [3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65,
118
+ 81, 97, 113, 129, 145, 161, 177, 193]
119
+ # Proth prime
120
+ A080076 = [3, 5, 13, 17, 41, 97, 113, 193]
121
+
122
+ for n in range(200):
123
+ if n in A080075:
124
+ assert proth_test(n) == (n in A080076)
125
+ else:
126
+ raises(ValueError, lambda: proth_test(n))
127
+
128
+
129
+ def test_lucas_lehmer_primality_test():
130
+ for p in sieve.primerange(3, 100):
131
+ assert _lucas_lehmer_primality_test(p) == (p in MERSENNE_PRIME_EXPONENTS)
132
+
133
+
134
+ def test_is_mersenne_prime():
135
+ assert is_mersenne_prime(-3) is False
136
+ assert is_mersenne_prime(3) is True
137
+ assert is_mersenne_prime(10) is False
138
+ assert is_mersenne_prime(127) is True
139
+ assert is_mersenne_prime(511) is False
140
+ assert is_mersenne_prime(131071) is True
141
+ assert is_mersenne_prime(2147483647) is True
142
+
143
+
144
+ def test_isprime():
145
+ s = Sieve()
146
+ s.extend(100000)
147
+ ps = set(s.primerange(2, 100001))
148
+ for n in range(100001):
149
+ # if (n in ps) != isprime(n): print n
150
+ assert (n in ps) == isprime(n)
151
+ assert isprime(179424673)
152
+ assert isprime(20678048681)
153
+ assert isprime(1968188556461)
154
+ assert isprime(2614941710599)
155
+ assert isprime(65635624165761929287)
156
+ assert isprime(1162566711635022452267983)
157
+ assert isprime(77123077103005189615466924501)
158
+ assert isprime(3991617775553178702574451996736229)
159
+ assert isprime(273952953553395851092382714516720001799)
160
+ assert isprime(int('''
161
+ 531137992816767098689588206552468627329593117727031923199444138200403\
162
+ 559860852242739162502265229285668889329486246501015346579337652707239\
163
+ 409519978766587351943831270835393219031728127'''))
164
+
165
+ # Some Mersenne primes
166
+ assert isprime(2**61 - 1)
167
+ assert isprime(2**89 - 1)
168
+ assert isprime(2**607 - 1)
169
+ # (but not all Mersenne's are primes
170
+ assert not isprime(2**601 - 1)
171
+
172
+ # pseudoprimes
173
+ #-------------
174
+ # to some small bases
175
+ assert not isprime(2152302898747)
176
+ assert not isprime(3474749660383)
177
+ assert not isprime(341550071728321)
178
+ assert not isprime(3825123056546413051)
179
+ # passes the base set [2, 3, 7, 61, 24251]
180
+ assert not isprime(9188353522314541)
181
+ # large examples
182
+ assert not isprime(877777777777777777777777)
183
+ # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html
184
+ assert not isprime(318665857834031151167461)
185
+ # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html
186
+ assert not isprime(564132928021909221014087501701)
187
+ # Arnault's 1993 number; a factor of it is
188
+ # 400958216639499605418306452084546853005188166041132508774506\
189
+ # 204738003217070119624271622319159721973358216316508535816696\
190
+ # 9145233813917169287527980445796800452592031836601
191
+ assert not isprime(int('''
192
+ 803837457453639491257079614341942108138837688287558145837488917522297\
193
+ 427376533365218650233616396004545791504202360320876656996676098728404\
194
+ 396540823292873879185086916685732826776177102938969773947016708230428\
195
+ 687109997439976544144845341155872450633409279022275296229414984230688\
196
+ 1685404326457534018329786111298960644845216191652872597534901'''))
197
+ # Arnault's 1995 number; can be factored as
198
+ # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is
199
+ # 296744956686855105501541746429053327307719917998530433509950\
200
+ # 755312768387531717701995942385964281211880336647542183455624\
201
+ # 93168782883
202
+ assert not isprime(int('''
203
+ 288714823805077121267142959713039399197760945927972270092651602419743\
204
+ 230379915273311632898314463922594197780311092934965557841894944174093\
205
+ 380561511397999942154241693397290542371100275104208013496673175515285\
206
+ 922696291677532547504444585610194940420003990443211677661994962953925\
207
+ 045269871932907037356403227370127845389912612030924484149472897688540\
208
+ 6024976768122077071687938121709811322297802059565867'''))
209
+ sieve.extend(3000)
210
+ assert isprime(2819)
211
+ assert not isprime(2931)
212
+ raises(ValueError, lambda: isprime(2.0))
213
+ raises(ValueError, lambda: isprime(Float(2)))
214
+
215
+
216
+ def test_is_square():
217
+ assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16]
218
+
219
+ # issue #17044
220
+ assert not is_square(60 ** 3)
221
+ assert not is_square(60 ** 5)
222
+ assert not is_square(84 ** 7)
223
+ assert not is_square(105 ** 9)
224
+ assert not is_square(120 ** 3)
225
+
226
+ def test_is_gaussianprime():
227
+ assert is_gaussian_prime(7*I)
228
+ assert is_gaussian_prime(7)
229
+ assert is_gaussian_prime(2 + 3*I)
230
+ assert not is_gaussian_prime(2 + 2*I)
231
+
232
+
233
+ def test_issue_27145():
234
+ #https://github.com/sympy/sympy/issues/27145
235
+ assert [mr(i,[2,3,5,7]) for i in (1, 2, 6)] == [False, True, False]
.venv/Lib/site-packages/sympy/ntheory/tests/test_qs.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from sympy.core.random import _randint
5
+ from sympy.ntheory import qs, qs_factor
6
+ from sympy.ntheory.qs import SievePolynomial, _generate_factor_base, \
7
+ _generate_polynomial, \
8
+ _gen_sieve_array, _check_smoothness, _trial_division_stage, _find_factor
9
+ from sympy.testing.pytest import slow
10
+
11
+
12
+ @slow
13
+ def test_qs_1():
14
+ assert qs(10009202107, 100, 10000) == {100043, 100049}
15
+ assert qs(211107295182713951054568361, 1000, 10000) == \
16
+ {13791315212531, 15307263442931}
17
+ assert qs(980835832582657*990377764891511, 2000, 10000) == \
18
+ {980835832582657, 990377764891511}
19
+ assert qs(18640889198609*20991129234731, 1000, 50000) == \
20
+ {18640889198609, 20991129234731}
21
+
22
+
23
+ def test_qs_2() -> None:
24
+ n = 10009202107
25
+ M = 50
26
+ sieve_poly = SievePolynomial(10, 80, n)
27
+ assert sieve_poly.eval_v(10) == sieve_poly.eval_u(10)**2 - n == -10009169707
28
+ assert sieve_poly.eval_v(5) == sieve_poly.eval_u(5)**2 - n == -10009185207
29
+
30
+ idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n)
31
+ assert idx_1000 == 82
32
+ assert [factor_base[i].prime for i in range(15)] == \
33
+ [2, 3, 7, 11, 17, 19, 29, 31, 43, 59, 61, 67, 71, 73, 79]
34
+ assert [factor_base[i].tmem_p for i in range(15)] == \
35
+ [1, 1, 3, 5, 3, 6, 6, 14, 1, 16, 24, 22, 18, 22, 15]
36
+ assert [factor_base[i].log_p for i in range(5)] == \
37
+ [710, 1125, 1993, 2455, 2901]
38
+
39
+ it = _generate_polynomial(
40
+ n, M, factor_base, idx_1000, idx_5000, _randint(0))
41
+ g = next(it)
42
+ assert g.a == 1133107
43
+ assert g.b == 682543
44
+ assert [factor_base[i].soln1 for i in range(15)] == \
45
+ [0, 0, 3, 7, 13, 0, 8, 19, 9, 43, 27, 25, 63, 29, 19]
46
+ assert [factor_base[i].soln2 for i in range(15)] == \
47
+ [0, 1, 1, 3, 12, 16, 15, 6, 15, 1, 56, 55, 61, 58, 16]
48
+ assert [factor_base[i].b_ainv for i in range(5)] == \
49
+ [[0, 0], [0, 2], [3, 0], [3, 9], [13, 13]]
50
+
51
+ g_1 = next(it)
52
+ assert g_1.a == 1133107
53
+ assert g_1.b == 136765
54
+
55
+ sieve_array = _gen_sieve_array(M, factor_base)
56
+ assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710]
57
+
58
+ assert _check_smoothness(9645, factor_base) == (36028797018963972, 5)
59
+ assert _check_smoothness(210313, factor_base) == (20992, 1)
60
+
61
+ partial_relations: dict[int, tuple[int, int]] = {}
62
+ smooth_relation, proper_factor = _trial_division_stage(
63
+ n, M, factor_base, sieve_array, sieve_poly, partial_relations,
64
+ ERROR_TERM=25*2**10)
65
+
66
+ assert partial_relations == {
67
+ 8699: (440, -10009008507, 75557863761098695507973),
68
+ 166741: (490, -10008962007, 524341),
69
+ 131449: (530, -10008921207, 664613997892457936451903530140172325),
70
+ 6653: (550, -10008899607, 19342813113834066795307021)
71
+ }
72
+ assert [smooth_relation[i][0] for i in range(5)] == [
73
+ -250, 1064469, 72819, 231957, 44167]
74
+ assert [smooth_relation[i][1] for i in range(5)] == [
75
+ -10009139607, 1133094251961, 5302606761, 53804049849, 1950723889]
76
+ assert smooth_relation[0][2] == 89213869829863962596973701078031812362502145
77
+ assert proper_factor == set()
78
+
79
+
80
+ def test_qs_3():
81
+ N = 1817
82
+ smooth_relations = [
83
+ (2455024, 637, 8),
84
+ (-27993000, 81536, 10),
85
+ (11461840, 12544, 0),
86
+ (149, 20384, 10),
87
+ (-31138074, 19208, 2)
88
+ ]
89
+ assert next(_find_factor(N, smooth_relations, 4)) == 23
90
+
91
+
92
+ def test_qs_4():
93
+ N = 10007**2 * 10009 * 10037**3 * 10039
94
+ for factor in qs(N, 1000, 2000):
95
+ assert N % factor == 0
96
+ N //= factor
97
+
98
+
99
+ def test_qs_factor():
100
+ assert qs_factor(1009 * 100003, 2000, 10000) == {1009: 1, 100003: 1}
101
+ n = 1009**2 * 2003**2*30011*400009
102
+ factors = qs_factor(n, 2000, 10000)
103
+ assert len(factors) > 1
104
+ assert math.prod(p**e for p, e in factors.items()) == n
105
+
106
+
107
+ def test_issue_27616():
108
+ #https://github.com/sympy/sympy/issues/27616
109
+ N = 9804659461513846513 + 1
110
+ assert qs(N, 5000, 20000) is not None
.venv/Lib/site-packages/sympy/ntheory/tests/test_residue.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from sympy.core.containers import Tuple
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Dummy, Symbol)
5
+ from sympy.functions.combinatorial.numbers import totient
6
+ from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \
7
+ legendre_symbol, jacobi_symbol, primerange, sqrt_mod, \
8
+ primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \
9
+ sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, \
10
+ polynomial_congruence, sieve
11
+ from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \
12
+ _primitive_root_prime_power_iter, _primitive_root_prime_power2_iter, \
13
+ _nthroot_mod_prime_power, _discrete_log_trial_mul, _discrete_log_shanks_steps, \
14
+ _discrete_log_pollard_rho, _discrete_log_index_calculus, _discrete_log_pohlig_hellman, \
15
+ _binomial_mod_prime_power, binomial_mod
16
+ from sympy.polys.domains import ZZ
17
+ from sympy.testing.pytest import raises
18
+ from sympy.core.random import randint, choice
19
+
20
+
21
+ def test_residue():
22
+ assert n_order(2, 13) == 12
23
+ assert [n_order(a, 7) for a in range(1, 7)] == \
24
+ [1, 3, 6, 3, 6, 2]
25
+ assert n_order(5, 17) == 16
26
+ assert n_order(17, 11) == n_order(6, 11)
27
+ assert n_order(101, 119) == 6
28
+ assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650
29
+ raises(ValueError, lambda: n_order(6, 9))
30
+
31
+ assert is_primitive_root(2, 7) is False
32
+ assert is_primitive_root(3, 8) is False
33
+ assert is_primitive_root(11, 14) is False
34
+ assert is_primitive_root(12, 17) == is_primitive_root(29, 17)
35
+ raises(ValueError, lambda: is_primitive_root(3, 6))
36
+
37
+ for p in primerange(3, 100):
38
+ li = list(_primitive_root_prime_iter(p))
39
+ assert li[0] == min(li)
40
+ for g in li:
41
+ assert n_order(g, p) == p - 1
42
+ assert len(li) == totient(totient(p))
43
+ for e in range(1, 4):
44
+ li_power = list(_primitive_root_prime_power_iter(p, e))
45
+ li_power2 = list(_primitive_root_prime_power2_iter(p, e))
46
+ assert len(li_power) == len(li_power2) == totient(totient(p**e))
47
+ assert primitive_root(97) == 5
48
+ assert n_order(primitive_root(97, False), 97) == totient(97)
49
+ assert primitive_root(97**2) == 5
50
+ assert n_order(primitive_root(97**2, False), 97**2) == totient(97**2)
51
+ assert primitive_root(40487) == 5
52
+ assert n_order(primitive_root(40487, False), 40487) == totient(40487)
53
+ # note that primitive_root(40487) + 40487 = 40492 is a primitive root
54
+ # of 40487**2, but it is not the smallest
55
+ assert primitive_root(40487**2) == 10
56
+ assert n_order(primitive_root(40487**2, False), 40487**2) == totient(40487**2)
57
+ assert primitive_root(82) == 7
58
+ assert n_order(primitive_root(82, False), 82) == totient(82)
59
+ p = 10**50 + 151
60
+ assert primitive_root(p) == 11
61
+ assert n_order(primitive_root(p, False), p) == totient(p)
62
+ assert primitive_root(2*p) == 11
63
+ assert n_order(primitive_root(2*p, False), 2*p) == totient(2*p)
64
+ assert primitive_root(p**2) == 11
65
+ assert n_order(primitive_root(p**2, False), p**2) == totient(p**2)
66
+ assert primitive_root(4 * 11) is None and primitive_root(4 * 11, False) is None
67
+ assert primitive_root(15) is None and primitive_root(15, False) is None
68
+ raises(ValueError, lambda: primitive_root(-3))
69
+
70
+ assert is_quad_residue(3, 7) is False
71
+ assert is_quad_residue(10, 13) is True
72
+ assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139)
73
+ assert is_quad_residue(207, 251) is True
74
+ assert is_quad_residue(0, 1) is True
75
+ assert is_quad_residue(1, 1) is True
76
+ assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True
77
+ assert is_quad_residue(1, 4) is True
78
+ assert is_quad_residue(2, 27) is False
79
+ assert is_quad_residue(13122380800, 13604889600) is True
80
+ assert [j for j in range(14) if is_quad_residue(j, 14)] == \
81
+ [0, 1, 2, 4, 7, 8, 9, 11]
82
+ raises(ValueError, lambda: is_quad_residue(1.1, 2))
83
+ raises(ValueError, lambda: is_quad_residue(2, 0))
84
+
85
+ assert quadratic_residues(S.One) == [0]
86
+ assert quadratic_residues(1) == [0]
87
+ assert quadratic_residues(12) == [0, 1, 4, 9]
88
+ assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12]
89
+ assert [len(quadratic_residues(i)) for i in range(1, 20)] == \
90
+ [1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10]
91
+
92
+ assert list(sqrt_mod_iter(6, 2)) == [0]
93
+ assert sqrt_mod(3, 13) == 4
94
+ assert sqrt_mod(3, -13) == 4
95
+ assert sqrt_mod(6, 23) == 11
96
+ assert sqrt_mod(345, 690) == 345
97
+ assert sqrt_mod(67, 101) == None
98
+ assert sqrt_mod(1020, 104729) == None
99
+
100
+ for p in range(3, 100):
101
+ d = defaultdict(list)
102
+ for i in range(p):
103
+ d[pow(i, 2, p)].append(i)
104
+ for i in range(1, p):
105
+ it = sqrt_mod_iter(i, p)
106
+ v = sqrt_mod(i, p, True)
107
+ if v:
108
+ v = sorted(v)
109
+ assert d[i] == v
110
+ else:
111
+ assert not d[i]
112
+
113
+ assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24]
114
+ assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78]
115
+ assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240]
116
+ assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72]
117
+ assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\
118
+ 126, 144, 153, 171, 180, 198, 207, 225, 234]
119
+ assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\
120
+ 333, 396, 414, 477, 495, 558, 576, 639, 657, 720]
121
+ assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\
122
+ 981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178]
123
+
124
+ for a, p in [(26214400, 32768000000), (26214400, 16384000000),
125
+ (262144, 1048576), (87169610025, 163443018796875),
126
+ (22315420166400, 167365651248000000)]:
127
+ assert pow(sqrt_mod(a, p), 2, p) == a
128
+
129
+ n = 70
130
+ a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2)
131
+ it = sqrt_mod_iter(a, p)
132
+ for i in range(10):
133
+ assert pow(next(it), 2, p) == a
134
+ a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3)
135
+ it = sqrt_mod_iter(a, p)
136
+ for i in range(2):
137
+ assert pow(next(it), 2, p) == a
138
+ n = 100
139
+ a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1)
140
+ it = sqrt_mod_iter(a, p)
141
+ for i in range(2):
142
+ assert pow(next(it), 2, p) == a
143
+
144
+ assert type(next(sqrt_mod_iter(9, 27))) is int
145
+ assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1))
146
+ assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1))
147
+
148
+ assert is_nthpow_residue(2, 1, 5)
149
+
150
+ #issue 10816
151
+ assert is_nthpow_residue(1, 0, 1) is False
152
+ assert is_nthpow_residue(1, 0, 2) is True
153
+ assert is_nthpow_residue(3, 0, 2) is True
154
+ assert is_nthpow_residue(0, 1, 8) is True
155
+ assert is_nthpow_residue(2, 3, 2) is True
156
+ assert is_nthpow_residue(2, 3, 9) is False
157
+ assert is_nthpow_residue(3, 5, 30) is True
158
+ assert is_nthpow_residue(21, 11, 20) is True
159
+ assert is_nthpow_residue(7, 10, 20) is False
160
+ assert is_nthpow_residue(5, 10, 20) is True
161
+ assert is_nthpow_residue(3, 10, 48) is False
162
+ assert is_nthpow_residue(1, 10, 40) is True
163
+ assert is_nthpow_residue(3, 10, 24) is False
164
+ assert is_nthpow_residue(1, 10, 24) is True
165
+ assert is_nthpow_residue(3, 10, 24) is False
166
+ assert is_nthpow_residue(2, 10, 48) is False
167
+ assert is_nthpow_residue(81, 3, 972) is False
168
+ assert is_nthpow_residue(243, 5, 5103) is True
169
+ assert is_nthpow_residue(243, 3, 1240029) is False
170
+ assert is_nthpow_residue(36010, 8, 87382) is True
171
+ assert is_nthpow_residue(28552, 6, 2218) is True
172
+ assert is_nthpow_residue(92712, 9, 50026) is True
173
+ x = {pow(i, 56, 1024) for i in range(1024)}
174
+ assert {a for a in range(1024) if is_nthpow_residue(a, 56, 1024)} == x
175
+ x = { pow(i, 256, 2048) for i in range(2048)}
176
+ assert {a for a in range(2048) if is_nthpow_residue(a, 256, 2048)} == x
177
+ x = { pow(i, 11, 324000) for i in range(1000)}
178
+ assert [ is_nthpow_residue(a, 11, 324000) for a in x]
179
+ x = { pow(i, 17, 22217575536) for i in range(1000)}
180
+ assert [ is_nthpow_residue(a, 17, 22217575536) for a in x]
181
+ assert is_nthpow_residue(676, 3, 5364)
182
+ assert is_nthpow_residue(9, 12, 36)
183
+ assert is_nthpow_residue(32, 10, 41)
184
+ assert is_nthpow_residue(4, 2, 64)
185
+ assert is_nthpow_residue(31, 4, 41)
186
+ assert not is_nthpow_residue(2, 2, 5)
187
+ assert is_nthpow_residue(8547, 12, 10007)
188
+ assert is_nthpow_residue(Dummy(even=True) + 3, 3, 2) == True
189
+ # _nthroot_mod_prime_power
190
+ for p in primerange(2, 10):
191
+ for a in range(3):
192
+ for n in range(3, 5):
193
+ ans = _nthroot_mod_prime_power(a, n, p, 1)
194
+ assert isinstance(ans, list)
195
+ if len(ans) == 0:
196
+ for b in range(p):
197
+ assert pow(b, n, p) != a % p
198
+ for k in range(2, 10):
199
+ assert _nthroot_mod_prime_power(a, n, p, k) == []
200
+ else:
201
+ for b in range(p):
202
+ pred = pow(b, n, p) == a % p
203
+ assert not(pred ^ (b in ans))
204
+ for k in range(2, 10):
205
+ ans = _nthroot_mod_prime_power(a, n, p, k)
206
+ if not ans:
207
+ break
208
+ for b in ans:
209
+ assert pow(b, n , p**k) == a
210
+
211
+ assert nthroot_mod(Dummy(odd=True), 3, 2) == 1
212
+ assert nthroot_mod(29, 31, 74) == 45
213
+ assert nthroot_mod(1801, 11, 2663) == 44
214
+ for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663),
215
+ (26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663),
216
+ (1714, 12, 2663), (28477, 9, 33343)]:
217
+ r = nthroot_mod(a, q, p)
218
+ assert pow(r, q, p) == a
219
+ assert nthroot_mod(11, 3, 109) is None
220
+ assert nthroot_mod(16, 5, 36, True) == [4, 22]
221
+ assert nthroot_mod(9, 16, 36, True) == [3, 9, 15, 21, 27, 33]
222
+ assert nthroot_mod(4, 3, 3249000) is None
223
+ assert nthroot_mod(36010, 8, 87382, True) == [40208, 47174]
224
+ assert nthroot_mod(0, 12, 37, True) == [0]
225
+ assert nthroot_mod(0, 7, 100, True) == [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
226
+ assert nthroot_mod(4, 4, 27, True) == [5, 22]
227
+ assert nthroot_mod(4, 4, 121, True) == [19, 102]
228
+ assert nthroot_mod(2, 3, 7, True) == []
229
+ for p in range(1, 20):
230
+ for a in range(p):
231
+ for n in range(1, p):
232
+ ans = nthroot_mod(a, n, p, True)
233
+ assert isinstance(ans, list)
234
+ for b in range(p):
235
+ pred = pow(b, n, p) == a
236
+ assert not(pred ^ (b in ans))
237
+ ans2 = nthroot_mod(a, n, p, False)
238
+ if ans2 is None:
239
+ assert ans == []
240
+ else:
241
+ assert ans2 in ans
242
+
243
+ x = Symbol('x', positive=True)
244
+ i = Symbol('i', integer=True)
245
+ assert _discrete_log_trial_mul(587, 2**7, 2) == 7
246
+ assert _discrete_log_trial_mul(941, 7**18, 7) == 18
247
+ assert _discrete_log_trial_mul(389, 3**81, 3) == 81
248
+ assert _discrete_log_trial_mul(191, 19**123, 19) == 123
249
+ assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2
250
+ assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19
251
+ assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71
252
+ assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321
253
+ assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6
254
+ assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19
255
+ assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40
256
+ assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333
257
+ raises(ValueError, lambda: _discrete_log_pollard_rho(11, 7, 31, rseed=0))
258
+ raises(ValueError, lambda: _discrete_log_pollard_rho(227, 3**7, 5, rseed=0))
259
+ assert _discrete_log_index_calculus(983, 948, 2, 491) == 183
260
+ assert _discrete_log_index_calculus(633383, 21794, 2, 316691) == 68048
261
+ assert _discrete_log_index_calculus(941762639, 68822582, 2, 470881319) == 338029275
262
+ assert _discrete_log_index_calculus(999231337607, 888188918786, 2, 499615668803) == 142811376514
263
+ assert _discrete_log_index_calculus(47747730623, 19410045286, 43425105668, 645239603) == 590504662
264
+ assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9
265
+ assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31
266
+ assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98
267
+ assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444
268
+ assert discrete_log(1, 0, 2) == 0
269
+ raises(ValueError, lambda: discrete_log(-4, 1, 3))
270
+ raises(ValueError, lambda: discrete_log(10, 3, 2))
271
+ assert discrete_log(587, 2**9, 2) == 9
272
+ assert discrete_log(2456747, 3**51, 3) == 51
273
+ assert discrete_log(32942478, 11**127, 11) == 127
274
+ assert discrete_log(432751500361, 7**324, 7) == 324
275
+ assert discrete_log(265390227570863,184500076053622, 2) == 17835221372061
276
+ assert discrete_log(22708823198678103974314518195029102158525052496759285596453269189798311427475159776411276642277139650833937,
277
+ 17463946429475485293747680247507700244427944625055089103624311227422110546803452417458985046168310373075327,
278
+ 123456) == 2068031853682195777930683306640554533145512201725884603914601918777510185469769997054750835368413389728895
279
+ args = 5779, 3528, 6215
280
+ assert discrete_log(*args) == 687
281
+ assert discrete_log(*Tuple(*args)) == 687
282
+ assert quadratic_congruence(400, 85, 125, 1600) == [295, 615, 935, 1255, 1575]
283
+ assert quadratic_congruence(3, 6, 5, 25) == [3, 20]
284
+ assert quadratic_congruence(120, 80, 175, 500) == []
285
+ assert quadratic_congruence(15, 14, 7, 2) == [1]
286
+ assert quadratic_congruence(8, 15, 7, 29) == [10, 28]
287
+ assert quadratic_congruence(160, 200, 300, 461) == [144, 431]
288
+ assert quadratic_congruence(100000, 123456, 7415263, 48112959837082048697) == [30417843635344493501, 36001135160550533083]
289
+ assert quadratic_congruence(65, 121, 72, 277) == [249, 252]
290
+ assert quadratic_congruence(5, 10, 14, 2) == [0]
291
+ assert quadratic_congruence(10, 17, 19, 2) == [1]
292
+ assert quadratic_congruence(10, 14, 20, 2) == [0, 1]
293
+ assert quadratic_congruence(2**48-7, 2**48-1, 4, 2**48) == [8249717183797, 31960993774868]
294
+ assert polynomial_congruence(6*x**5 + 10*x**4 + 5*x**3 + x**2 + x + 1,
295
+ 972000) == [220999, 242999, 463999, 485999, 706999, 728999, 949999, 971999]
296
+
297
+ assert polynomial_congruence(x**3 - 10*x**2 + 12*x - 82, 33075) == [30287]
298
+ assert polynomial_congruence(x**2 + x + 47, 2401) == [785, 1615]
299
+ assert polynomial_congruence(10*x**2 + 14*x + 20, 2) == [0, 1]
300
+ assert polynomial_congruence(x**3 + 3, 16) == [5]
301
+ assert polynomial_congruence(65*x**2 + 121*x + 72, 277) == [249, 252]
302
+ assert polynomial_congruence(x**4 - 4, 27) == [5, 22]
303
+ assert polynomial_congruence(35*x**3 - 6*x**2 - 567*x + 2308, 148225) == [86957,
304
+ 111157, 122531, 146731]
305
+ assert polynomial_congruence(x**16 - 9, 36) == [3, 9, 15, 21, 27, 33]
306
+ assert polynomial_congruence(x**6 - 2*x**5 - 35, 6125) == [3257]
307
+ raises(ValueError, lambda: polynomial_congruence(x**x, 6125))
308
+ raises(ValueError, lambda: polynomial_congruence(x**i, 6125))
309
+ raises(ValueError, lambda: polynomial_congruence(0.1*x**2 + 6, 100))
310
+
311
+ assert binomial_mod(-1, 1, 10) == 0
312
+ assert binomial_mod(1, -1, 10) == 0
313
+ raises(ValueError, lambda: binomial_mod(2, 1, -1))
314
+ assert binomial_mod(51, 10, 10) == 0
315
+ assert binomial_mod(10**3, 500, 3**6) == 567
316
+ assert binomial_mod(10**18 - 1, 123456789, 4) == 0
317
+ assert binomial_mod(10**18, 10**12, (10**5 + 3)**2) == 3744312326
318
+
319
+
320
+ def test_binomial_p_pow():
321
+ n, binomials, binomial = 1000, [1], 1
322
+ for i in range(1, n + 1):
323
+ binomial *= n - i + 1
324
+ binomial //= i
325
+ binomials.append(binomial)
326
+
327
+ # Test powers of two, which the algorithm treats slightly differently
328
+ trials_2 = 100
329
+ for _ in range(trials_2):
330
+ m, power = randint(0, n), randint(1, 20)
331
+ assert _binomial_mod_prime_power(n, m, 2, power) == binomials[m] % 2**power
332
+
333
+ # Test against other prime powers
334
+ primes = list(sieve.primerange(2*n))
335
+ trials = 1000
336
+ for _ in range(trials):
337
+ m, prime, power = randint(0, n), choice(primes), randint(1, 10)
338
+ assert _binomial_mod_prime_power(n, m, prime, power) == binomials[m] % prime**power
339
+
340
+
341
+ def test_deprecated_ntheory_symbolic_functions():
342
+ from sympy.testing.pytest import warns_deprecated_sympy
343
+
344
+ with warns_deprecated_sympy():
345
+ assert mobius(3) == -1
346
+ with warns_deprecated_sympy():
347
+ assert legendre_symbol(2, 3) == -1
348
+ with warns_deprecated_sympy():
349
+ assert jacobi_symbol(2, 3) == -1
.venv/Lib/site-packages/sympy/parsing/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Used for translating a string into a SymPy expression. """
2
+ __all__ = ['parse_expr']
3
+
4
+ from .sympy_parser import parse_expr
.venv/Lib/site-packages/sympy/parsing/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (350 Bytes). View file
 
.venv/Lib/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-312.pyc ADDED
Binary file (47 kB). View file
 
.venv/Lib/site-packages/sympy/parsing/ast_parser.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements the functionality to take any Python expression as a
3
+ string and fix all numbers and other things before evaluating it,
4
+ thus
5
+
6
+ 1/2
7
+
8
+ returns
9
+
10
+ Integer(1)/Integer(2)
11
+
12
+ We use the ast module for this. It is well documented at docs.python.org.
13
+
14
+ Some tips to understand how this works: use dump() to get a nice
15
+ representation of any node. Then write a string of what you want to get,
16
+ e.g. "Integer(1)", parse it, dump it and you'll see that you need to do
17
+ "Call(Name('Integer', Load()), [node], [], None, None)". You do not need
18
+ to bother with lineno and col_offset, just call fix_missing_locations()
19
+ before returning the node.
20
+ """
21
+
22
+ from sympy.core.basic import Basic
23
+ from sympy.core.sympify import SympifyError
24
+
25
+ from ast import parse, NodeTransformer, Call, Name, Load, \
26
+ fix_missing_locations, Constant, Tuple
27
+
28
+ class Transform(NodeTransformer):
29
+
30
+ def __init__(self, local_dict, global_dict):
31
+ NodeTransformer.__init__(self)
32
+ self.local_dict = local_dict
33
+ self.global_dict = global_dict
34
+
35
+ def visit_Constant(self, node):
36
+ if isinstance(node.value, int):
37
+ return fix_missing_locations(Call(func=Name('Integer', Load()),
38
+ args=[node], keywords=[]))
39
+ elif isinstance(node.value, float):
40
+ return fix_missing_locations(Call(func=Name('Float', Load()),
41
+ args=[node], keywords=[]))
42
+ return node
43
+
44
+ def visit_Name(self, node):
45
+ if node.id in self.local_dict:
46
+ return node
47
+ elif node.id in self.global_dict:
48
+ name_obj = self.global_dict[node.id]
49
+
50
+ if isinstance(name_obj, (Basic, type)) or callable(name_obj):
51
+ return node
52
+ elif node.id in ['True', 'False']:
53
+ return node
54
+ return fix_missing_locations(Call(func=Name('Symbol', Load()),
55
+ args=[Constant(node.id)], keywords=[]))
56
+
57
+ def visit_Lambda(self, node):
58
+ args = [self.visit(arg) for arg in node.args.args]
59
+ body = self.visit(node.body)
60
+ n = Call(func=Name('Lambda', Load()),
61
+ args=[Tuple(args, Load()), body], keywords=[])
62
+ return fix_missing_locations(n)
63
+
64
+ def parse_expr(s, local_dict):
65
+ """
66
+ Converts the string "s" to a SymPy expression, in local_dict.
67
+
68
+ It converts all numbers to Integers before feeding it to Python and
69
+ automatically creates Symbols.
70
+ """
71
+ global_dict = {}
72
+ exec('from sympy import *', global_dict)
73
+ try:
74
+ a = parse(s.strip(), mode="eval")
75
+ except SyntaxError:
76
+ raise SympifyError("Cannot parse %s." % repr(s))
77
+ a = Transform(local_dict, global_dict).visit(a)
78
+ e = compile(a, "<string>", "eval")
79
+ return eval(e, global_dict, local_dict)
.venv/Lib/site-packages/sympy/parsing/autolev/Autolev.g4 ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ grammar Autolev;
2
+
3
+ options {
4
+ language = Python3;
5
+ }
6
+
7
+ prog: stat+;
8
+
9
+ stat: varDecl
10
+ | functionCall
11
+ | codeCommands
12
+ | massDecl
13
+ | inertiaDecl
14
+ | assignment
15
+ | settings
16
+ ;
17
+
18
+ assignment: vec equals expr #vecAssign
19
+ | ID '[' index ']' equals expr #indexAssign
20
+ | ID diff? equals expr #regularAssign;
21
+
22
+ equals: ('='|'+='|'-='|':='|'*='|'/='|'^=');
23
+
24
+ index: expr (',' expr)* ;
25
+
26
+ diff: ('\'')+;
27
+
28
+ functionCall: ID '(' (expr (',' expr)*)? ')'
29
+ | (Mass|Inertia) '(' (ID (',' ID)*)? ')';
30
+
31
+ varDecl: varType varDecl2 (',' varDecl2)*;
32
+
33
+ varType: Newtonian|Frames|Bodies|Particles|Points|Constants
34
+ | Specifieds|Imaginary|Variables ('\'')*|MotionVariables ('\'')*;
35
+
36
+ varDecl2: ID ('{' INT ',' INT '}')? (('{' INT ':' INT (',' INT ':' INT)* '}'))? ('{' INT '}')? ('+'|'-')? ('\'')* ('=' expr)?;
37
+
38
+ ranges: ('{' INT ':' INT (',' INT ':' INT)* '}');
39
+
40
+ massDecl: Mass massDecl2 (',' massDecl2)*;
41
+
42
+ massDecl2: ID '=' expr;
43
+
44
+ inertiaDecl: Inertia ID ('(' ID ')')? (',' expr)+;
45
+
46
+ matrix: '[' expr ((','|';') expr)* ']';
47
+ matrixInOutput: (ID (ID '=' (FLOAT|INT)?))|FLOAT|INT;
48
+
49
+ codeCommands: units
50
+ | inputs
51
+ | outputs
52
+ | codegen
53
+ | commands;
54
+
55
+ settings: ID (EXP|ID|FLOAT|INT)?;
56
+
57
+ units: UnitSystem ID (',' ID)*;
58
+ inputs: Input inputs2 (',' inputs2)*;
59
+ id_diff: ID diff?;
60
+ inputs2: id_diff '=' expr expr?;
61
+ outputs: Output outputs2 (',' outputs2)*;
62
+ outputs2: expr expr?;
63
+ codegen: ID functionCall ('['matrixInOutput (',' matrixInOutput)*']')? ID'.'ID;
64
+
65
+ commands: Save ID'.'ID
66
+ | Encode ID (',' ID)*;
67
+
68
+ vec: ID ('>')+
69
+ | '0>'
70
+ | '1>>';
71
+
72
+ expr: expr '^'<assoc=right> expr # Exponent
73
+ | expr ('*'|'/') expr # MulDiv
74
+ | expr ('+'|'-') expr # AddSub
75
+ | EXP # exp
76
+ | '-' expr # negativeOne
77
+ | FLOAT # float
78
+ | INT # int
79
+ | ID('\'')* # id
80
+ | vec # VectorOrDyadic
81
+ | ID '['expr (',' expr)* ']' # Indexing
82
+ | functionCall # function
83
+ | matrix # matrices
84
+ | '(' expr ')' # parens
85
+ | expr '=' expr # idEqualsExpr
86
+ | expr ':' expr # colon
87
+ | ID? ranges ('\'')* # rangess
88
+ ;
89
+
90
+ // These are to take care of the case insensitivity of Autolev.
91
+ Mass: ('M'|'m')('A'|'a')('S'|'s')('S'|'s');
92
+ Inertia: ('I'|'i')('N'|'n')('E'|'e')('R'|'r')('T'|'t')('I'|'i')('A'|'a');
93
+ Input: ('I'|'i')('N'|'n')('P'|'p')('U'|'u')('T'|'t')('S'|'s')?;
94
+ Output: ('O'|'o')('U'|'u')('T'|'t')('P'|'p')('U'|'u')('T'|'t');
95
+ Save: ('S'|'s')('A'|'a')('V'|'v')('E'|'e');
96
+ UnitSystem: ('U'|'u')('N'|'n')('I'|'i')('T'|'t')('S'|'s')('Y'|'y')('S'|'s')('T'|'t')('E'|'e')('M'|'m');
97
+ Encode: ('E'|'e')('N'|'n')('C'|'c')('O'|'o')('D'|'d')('E'|'e');
98
+ Newtonian: ('N'|'n')('E'|'e')('W'|'w')('T'|'t')('O'|'o')('N'|'n')('I'|'i')('A'|'a')('N'|'n');
99
+ Frames: ('F'|'f')('R'|'r')('A'|'a')('M'|'m')('E'|'e')('S'|'s')?;
100
+ Bodies: ('B'|'b')('O'|'o')('D'|'d')('I'|'i')('E'|'e')('S'|'s')?;
101
+ Particles: ('P'|'p')('A'|'a')('R'|'r')('T'|'t')('I'|'i')('C'|'c')('L'|'l')('E'|'e')('S'|'s')?;
102
+ Points: ('P'|'p')('O'|'o')('I'|'i')('N'|'n')('T'|'t')('S'|'s')?;
103
+ Constants: ('C'|'c')('O'|'o')('N'|'n')('S'|'s')('T'|'t')('A'|'a')('N'|'n')('T'|'t')('S'|'s')?;
104
+ Specifieds: ('S'|'s')('P'|'p')('E'|'e')('C'|'c')('I'|'i')('F'|'f')('I'|'i')('E'|'e')('D'|'d')('S'|'s')?;
105
+ Imaginary: ('I'|'i')('M'|'m')('A'|'a')('G'|'g')('I'|'i')('N'|'n')('A'|'a')('R'|'r')('Y'|'y');
106
+ Variables: ('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
107
+ MotionVariables: ('M'|'m')('O'|'o')('T'|'t')('I'|'i')('O'|'o')('N'|'n')('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
108
+
109
+ fragment DIFF: ('\'')*;
110
+ fragment DIGIT: [0-9];
111
+ INT: [0-9]+ ; // match integers
112
+ FLOAT: DIGIT+ '.' DIGIT*
113
+ | '.' DIGIT+;
114
+ EXP: FLOAT 'E' INT
115
+ | FLOAT 'E' '-' INT;
116
+ LINE_COMMENT : '%' .*? '\r'? '\n' -> skip ;
117
+ ID: [a-zA-Z][a-zA-Z0-9_]*;
118
+ WS: [ \t\r\n&]+ -> skip ; // toss out whitespace
.venv/Lib/site-packages/sympy/parsing/autolev/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ from sympy.utilities.decorator import doctest_depends_on
3
+
4
+ @doctest_depends_on(modules=('antlr4',))
5
+ def parse_autolev(autolev_code, include_numeric=False):
6
+ """Parses Autolev code (version 4.1) to SymPy code.
7
+
8
+ Parameters
9
+ =========
10
+ autolev_code : Can be an str or any object with a readlines() method (such as a file handle or StringIO).
11
+ include_numeric : boolean, optional
12
+ If True NumPy, PyDy, or other numeric code is included for numeric evaluation lines in the Autolev code.
13
+
14
+ Returns
15
+ =======
16
+ sympy_code : str
17
+ Equivalent SymPy and/or numpy/pydy code as the input code.
18
+
19
+
20
+ Example (Double Pendulum)
21
+ =========================
22
+ >>> my_al_text = ("MOTIONVARIABLES' Q{2}', U{2}'",
23
+ ... "CONSTANTS L,M,G",
24
+ ... "NEWTONIAN N",
25
+ ... "FRAMES A,B",
26
+ ... "SIMPROT(N, A, 3, Q1)",
27
+ ... "SIMPROT(N, B, 3, Q2)",
28
+ ... "W_A_N>=U1*N3>",
29
+ ... "W_B_N>=U2*N3>",
30
+ ... "POINT O",
31
+ ... "PARTICLES P,R",
32
+ ... "P_O_P> = L*A1>",
33
+ ... "P_P_R> = L*B1>",
34
+ ... "V_O_N> = 0>",
35
+ ... "V2PTS(N, A, O, P)",
36
+ ... "V2PTS(N, B, P, R)",
37
+ ... "MASS P=M, R=M",
38
+ ... "Q1' = U1",
39
+ ... "Q2' = U2",
40
+ ... "GRAVITY(G*N1>)",
41
+ ... "ZERO = FR() + FRSTAR()",
42
+ ... "KANE()",
43
+ ... "INPUT M=1,G=9.81,L=1",
44
+ ... "INPUT Q1=.1,Q2=.2,U1=0,U2=0",
45
+ ... "INPUT TFINAL=10, INTEGSTP=.01",
46
+ ... "CODE DYNAMICS() some_filename.c")
47
+ >>> my_al_text = '\\n'.join(my_al_text)
48
+ >>> from sympy.parsing.autolev import parse_autolev
49
+ >>> print(parse_autolev(my_al_text, include_numeric=True))
50
+ import sympy.physics.mechanics as _me
51
+ import sympy as _sm
52
+ import math as m
53
+ import numpy as _np
54
+ <BLANKLINE>
55
+ q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
56
+ q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
57
+ l, m, g = _sm.symbols('l m g', real=True)
58
+ frame_n = _me.ReferenceFrame('n')
59
+ frame_a = _me.ReferenceFrame('a')
60
+ frame_b = _me.ReferenceFrame('b')
61
+ frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
62
+ frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
63
+ frame_a.set_ang_vel(frame_n, u1*frame_n.z)
64
+ frame_b.set_ang_vel(frame_n, u2*frame_n.z)
65
+ point_o = _me.Point('o')
66
+ particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
67
+ particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
68
+ particle_p.point.set_pos(point_o, l*frame_a.x)
69
+ particle_r.point.set_pos(particle_p.point, l*frame_b.x)
70
+ point_o.set_vel(frame_n, 0)
71
+ particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
72
+ particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
73
+ particle_p.mass = m
74
+ particle_r.mass = m
75
+ force_p = particle_p.mass*(g*frame_n.x)
76
+ force_r = particle_r.mass*(g*frame_n.x)
77
+ kd_eqs = [q1_d - u1, q2_d - u2]
78
+ forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
79
+ kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
80
+ fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
81
+ zero = fr+frstar
82
+ from pydy.system import System
83
+ sys = System(kane, constants = {l:1, m:1, g:9.81},
84
+ specifieds={},
85
+ initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
86
+ times = _np.linspace(0.0, 10, 10/.01))
87
+ <BLANKLINE>
88
+ y=sys.integrate()
89
+ <BLANKLINE>
90
+ """
91
+
92
+ _autolev = import_module(
93
+ 'sympy.parsing.autolev._parse_autolev_antlr',
94
+ import_kwargs={'fromlist': ['X']})
95
+
96
+ if _autolev is not None:
97
+ return _autolev.parse_autolev(autolev_code, include_numeric)
.venv/Lib/site-packages/sympy/parsing/autolev/_antlr/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
.venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
6
+ from antlr4 import *
7
+ from io import StringIO
8
+ import sys
9
+ if sys.version_info[1] > 5:
10
+ from typing import TextIO
11
+ else:
12
+ from typing.io import TextIO
13
+
14
+
15
+ def serializedATN():
16
+ return [
17
+ 4,0,49,393,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
18
+ 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
19
+ 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
20
+ 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
21
+ 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
22
+ 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
23
+ 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
24
+ 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,1,0,1,0,1,1,
25
+ 1,1,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,
26
+ 1,7,1,7,1,8,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12,1,13,1,
27
+ 13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,
28
+ 20,1,20,1,21,1,21,1,21,1,22,1,22,1,22,1,22,1,23,1,23,1,24,1,24,1,
29
+ 25,1,25,1,26,1,26,1,26,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,
30
+ 27,1,27,1,28,1,28,1,28,1,28,1,28,1,28,3,28,184,8,28,1,29,1,29,1,
31
+ 29,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,31,1,31,1,31,1,
32
+ 31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,
33
+ 32,1,32,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,34,1,
34
+ 34,1,34,1,34,1,34,1,34,3,34,232,8,34,1,35,1,35,1,35,1,35,1,35,1,
35
+ 35,3,35,240,8,35,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,3,
36
+ 36,251,8,36,1,37,1,37,1,37,1,37,1,37,1,37,3,37,259,8,37,1,38,1,38,
37
+ 1,38,1,38,1,38,1,38,1,38,1,38,1,38,3,38,270,8,38,1,39,1,39,1,39,
38
+ 1,39,1,39,1,39,1,39,1,39,1,39,1,39,3,39,282,8,39,1,40,1,40,1,40,
39
+ 1,40,1,40,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41,
40
+ 1,41,1,41,1,41,3,41,303,8,41,1,42,1,42,1,42,1,42,1,42,1,42,1,42,
41
+ 1,42,1,42,1,42,1,42,1,42,1,42,1,42,1,42,3,42,320,8,42,1,43,5,43,
42
+ 323,8,43,10,43,12,43,326,9,43,1,44,1,44,1,45,4,45,331,8,45,11,45,
43
+ 12,45,332,1,46,4,46,336,8,46,11,46,12,46,337,1,46,1,46,5,46,342,
44
+ 8,46,10,46,12,46,345,9,46,1,46,1,46,4,46,349,8,46,11,46,12,46,350,
45
+ 3,46,353,8,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,3,47,
46
+ 364,8,47,1,48,1,48,5,48,368,8,48,10,48,12,48,371,9,48,1,48,3,48,
47
+ 374,8,48,1,48,1,48,1,48,1,48,1,49,1,49,5,49,382,8,49,10,49,12,49,
48
+ 385,9,49,1,50,4,50,388,8,50,11,50,12,50,389,1,50,1,50,1,369,0,51,
49
+ 1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,
50
+ 27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,
51
+ 49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,
52
+ 71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,0,89,0,91,44,
53
+ 93,45,95,46,97,47,99,48,101,49,1,0,24,2,0,77,77,109,109,2,0,65,65,
54
+ 97,97,2,0,83,83,115,115,2,0,73,73,105,105,2,0,78,78,110,110,2,0,
55
+ 69,69,101,101,2,0,82,82,114,114,2,0,84,84,116,116,2,0,80,80,112,
56
+ 112,2,0,85,85,117,117,2,0,79,79,111,111,2,0,86,86,118,118,2,0,89,
57
+ 89,121,121,2,0,67,67,99,99,2,0,68,68,100,100,2,0,87,87,119,119,2,
58
+ 0,70,70,102,102,2,0,66,66,98,98,2,0,76,76,108,108,2,0,71,71,103,
59
+ 103,1,0,48,57,2,0,65,90,97,122,4,0,48,57,65,90,95,95,97,122,4,0,
60
+ 9,10,13,13,32,32,38,38,410,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,
61
+ 7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,
62
+ 1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,
63
+ 1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37,
64
+ 1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,47,
65
+ 1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,57,
66
+ 1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67,
67
+ 1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,
68
+ 1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,91,
69
+ 1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99,1,0,0,0,0,101,
70
+ 1,0,0,0,1,103,1,0,0,0,3,105,1,0,0,0,5,107,1,0,0,0,7,109,1,0,0,0,
71
+ 9,112,1,0,0,0,11,115,1,0,0,0,13,118,1,0,0,0,15,121,1,0,0,0,17,124,
72
+ 1,0,0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0,
73
+ 0,0,27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0,
74
+ 35,143,1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151,
75
+ 1,0,0,0,45,154,1,0,0,0,47,158,1,0,0,0,49,160,1,0,0,0,51,162,1,0,
76
+ 0,0,53,164,1,0,0,0,55,169,1,0,0,0,57,177,1,0,0,0,59,185,1,0,0,0,
77
+ 61,192,1,0,0,0,63,197,1,0,0,0,65,208,1,0,0,0,67,215,1,0,0,0,69,225,
78
+ 1,0,0,0,71,233,1,0,0,0,73,241,1,0,0,0,75,252,1,0,0,0,77,260,1,0,
79
+ 0,0,79,271,1,0,0,0,81,283,1,0,0,0,83,293,1,0,0,0,85,304,1,0,0,0,
80
+ 87,324,1,0,0,0,89,327,1,0,0,0,91,330,1,0,0,0,93,352,1,0,0,0,95,363,
81
+ 1,0,0,0,97,365,1,0,0,0,99,379,1,0,0,0,101,387,1,0,0,0,103,104,5,
82
+ 91,0,0,104,2,1,0,0,0,105,106,5,93,0,0,106,4,1,0,0,0,107,108,5,61,
83
+ 0,0,108,6,1,0,0,0,109,110,5,43,0,0,110,111,5,61,0,0,111,8,1,0,0,
84
+ 0,112,113,5,45,0,0,113,114,5,61,0,0,114,10,1,0,0,0,115,116,5,58,
85
+ 0,0,116,117,5,61,0,0,117,12,1,0,0,0,118,119,5,42,0,0,119,120,5,61,
86
+ 0,0,120,14,1,0,0,0,121,122,5,47,0,0,122,123,5,61,0,0,123,16,1,0,
87
+ 0,0,124,125,5,94,0,0,125,126,5,61,0,0,126,18,1,0,0,0,127,128,5,44,
88
+ 0,0,128,20,1,0,0,0,129,130,5,39,0,0,130,22,1,0,0,0,131,132,5,40,
89
+ 0,0,132,24,1,0,0,0,133,134,5,41,0,0,134,26,1,0,0,0,135,136,5,123,
90
+ 0,0,136,28,1,0,0,0,137,138,5,125,0,0,138,30,1,0,0,0,139,140,5,58,
91
+ 0,0,140,32,1,0,0,0,141,142,5,43,0,0,142,34,1,0,0,0,143,144,5,45,
92
+ 0,0,144,36,1,0,0,0,145,146,5,59,0,0,146,38,1,0,0,0,147,148,5,46,
93
+ 0,0,148,40,1,0,0,0,149,150,5,62,0,0,150,42,1,0,0,0,151,152,5,48,
94
+ 0,0,152,153,5,62,0,0,153,44,1,0,0,0,154,155,5,49,0,0,155,156,5,62,
95
+ 0,0,156,157,5,62,0,0,157,46,1,0,0,0,158,159,5,94,0,0,159,48,1,0,
96
+ 0,0,160,161,5,42,0,0,161,50,1,0,0,0,162,163,5,47,0,0,163,52,1,0,
97
+ 0,0,164,165,7,0,0,0,165,166,7,1,0,0,166,167,7,2,0,0,167,168,7,2,
98
+ 0,0,168,54,1,0,0,0,169,170,7,3,0,0,170,171,7,4,0,0,171,172,7,5,0,
99
+ 0,172,173,7,6,0,0,173,174,7,7,0,0,174,175,7,3,0,0,175,176,7,1,0,
100
+ 0,176,56,1,0,0,0,177,178,7,3,0,0,178,179,7,4,0,0,179,180,7,8,0,0,
101
+ 180,181,7,9,0,0,181,183,7,7,0,0,182,184,7,2,0,0,183,182,1,0,0,0,
102
+ 183,184,1,0,0,0,184,58,1,0,0,0,185,186,7,10,0,0,186,187,7,9,0,0,
103
+ 187,188,7,7,0,0,188,189,7,8,0,0,189,190,7,9,0,0,190,191,7,7,0,0,
104
+ 191,60,1,0,0,0,192,193,7,2,0,0,193,194,7,1,0,0,194,195,7,11,0,0,
105
+ 195,196,7,5,0,0,196,62,1,0,0,0,197,198,7,9,0,0,198,199,7,4,0,0,199,
106
+ 200,7,3,0,0,200,201,7,7,0,0,201,202,7,2,0,0,202,203,7,12,0,0,203,
107
+ 204,7,2,0,0,204,205,7,7,0,0,205,206,7,5,0,0,206,207,7,0,0,0,207,
108
+ 64,1,0,0,0,208,209,7,5,0,0,209,210,7,4,0,0,210,211,7,13,0,0,211,
109
+ 212,7,10,0,0,212,213,7,14,0,0,213,214,7,5,0,0,214,66,1,0,0,0,215,
110
+ 216,7,4,0,0,216,217,7,5,0,0,217,218,7,15,0,0,218,219,7,7,0,0,219,
111
+ 220,7,10,0,0,220,221,7,4,0,0,221,222,7,3,0,0,222,223,7,1,0,0,223,
112
+ 224,7,4,0,0,224,68,1,0,0,0,225,226,7,16,0,0,226,227,7,6,0,0,227,
113
+ 228,7,1,0,0,228,229,7,0,0,0,229,231,7,5,0,0,230,232,7,2,0,0,231,
114
+ 230,1,0,0,0,231,232,1,0,0,0,232,70,1,0,0,0,233,234,7,17,0,0,234,
115
+ 235,7,10,0,0,235,236,7,14,0,0,236,237,7,3,0,0,237,239,7,5,0,0,238,
116
+ 240,7,2,0,0,239,238,1,0,0,0,239,240,1,0,0,0,240,72,1,0,0,0,241,242,
117
+ 7,8,0,0,242,243,7,1,0,0,243,244,7,6,0,0,244,245,7,7,0,0,245,246,
118
+ 7,3,0,0,246,247,7,13,0,0,247,248,7,18,0,0,248,250,7,5,0,0,249,251,
119
+ 7,2,0,0,250,249,1,0,0,0,250,251,1,0,0,0,251,74,1,0,0,0,252,253,7,
120
+ 8,0,0,253,254,7,10,0,0,254,255,7,3,0,0,255,256,7,4,0,0,256,258,7,
121
+ 7,0,0,257,259,7,2,0,0,258,257,1,0,0,0,258,259,1,0,0,0,259,76,1,0,
122
+ 0,0,260,261,7,13,0,0,261,262,7,10,0,0,262,263,7,4,0,0,263,264,7,
123
+ 2,0,0,264,265,7,7,0,0,265,266,7,1,0,0,266,267,7,4,0,0,267,269,7,
124
+ 7,0,0,268,270,7,2,0,0,269,268,1,0,0,0,269,270,1,0,0,0,270,78,1,0,
125
+ 0,0,271,272,7,2,0,0,272,273,7,8,0,0,273,274,7,5,0,0,274,275,7,13,
126
+ 0,0,275,276,7,3,0,0,276,277,7,16,0,0,277,278,7,3,0,0,278,279,7,5,
127
+ 0,0,279,281,7,14,0,0,280,282,7,2,0,0,281,280,1,0,0,0,281,282,1,0,
128
+ 0,0,282,80,1,0,0,0,283,284,7,3,0,0,284,285,7,0,0,0,285,286,7,1,0,
129
+ 0,286,287,7,19,0,0,287,288,7,3,0,0,288,289,7,4,0,0,289,290,7,1,0,
130
+ 0,290,291,7,6,0,0,291,292,7,12,0,0,292,82,1,0,0,0,293,294,7,11,0,
131
+ 0,294,295,7,1,0,0,295,296,7,6,0,0,296,297,7,3,0,0,297,298,7,1,0,
132
+ 0,298,299,7,17,0,0,299,300,7,18,0,0,300,302,7,5,0,0,301,303,7,2,
133
+ 0,0,302,301,1,0,0,0,302,303,1,0,0,0,303,84,1,0,0,0,304,305,7,0,0,
134
+ 0,305,306,7,10,0,0,306,307,7,7,0,0,307,308,7,3,0,0,308,309,7,10,
135
+ 0,0,309,310,7,4,0,0,310,311,7,11,0,0,311,312,7,1,0,0,312,313,7,6,
136
+ 0,0,313,314,7,3,0,0,314,315,7,1,0,0,315,316,7,17,0,0,316,317,7,18,
137
+ 0,0,317,319,7,5,0,0,318,320,7,2,0,0,319,318,1,0,0,0,319,320,1,0,
138
+ 0,0,320,86,1,0,0,0,321,323,5,39,0,0,322,321,1,0,0,0,323,326,1,0,
139
+ 0,0,324,322,1,0,0,0,324,325,1,0,0,0,325,88,1,0,0,0,326,324,1,0,0,
140
+ 0,327,328,7,20,0,0,328,90,1,0,0,0,329,331,7,20,0,0,330,329,1,0,0,
141
+ 0,331,332,1,0,0,0,332,330,1,0,0,0,332,333,1,0,0,0,333,92,1,0,0,0,
142
+ 334,336,3,89,44,0,335,334,1,0,0,0,336,337,1,0,0,0,337,335,1,0,0,
143
+ 0,337,338,1,0,0,0,338,339,1,0,0,0,339,343,5,46,0,0,340,342,3,89,
144
+ 44,0,341,340,1,0,0,0,342,345,1,0,0,0,343,341,1,0,0,0,343,344,1,0,
145
+ 0,0,344,353,1,0,0,0,345,343,1,0,0,0,346,348,5,46,0,0,347,349,3,89,
146
+ 44,0,348,347,1,0,0,0,349,350,1,0,0,0,350,348,1,0,0,0,350,351,1,0,
147
+ 0,0,351,353,1,0,0,0,352,335,1,0,0,0,352,346,1,0,0,0,353,94,1,0,0,
148
+ 0,354,355,3,93,46,0,355,356,5,69,0,0,356,357,3,91,45,0,357,364,1,
149
+ 0,0,0,358,359,3,93,46,0,359,360,5,69,0,0,360,361,5,45,0,0,361,362,
150
+ 3,91,45,0,362,364,1,0,0,0,363,354,1,0,0,0,363,358,1,0,0,0,364,96,
151
+ 1,0,0,0,365,369,5,37,0,0,366,368,9,0,0,0,367,366,1,0,0,0,368,371,
152
+ 1,0,0,0,369,370,1,0,0,0,369,367,1,0,0,0,370,373,1,0,0,0,371,369,
153
+ 1,0,0,0,372,374,5,13,0,0,373,372,1,0,0,0,373,374,1,0,0,0,374,375,
154
+ 1,0,0,0,375,376,5,10,0,0,376,377,1,0,0,0,377,378,6,48,0,0,378,98,
155
+ 1,0,0,0,379,383,7,21,0,0,380,382,7,22,0,0,381,380,1,0,0,0,382,385,
156
+ 1,0,0,0,383,381,1,0,0,0,383,384,1,0,0,0,384,100,1,0,0,0,385,383,
157
+ 1,0,0,0,386,388,7,23,0,0,387,386,1,0,0,0,388,389,1,0,0,0,389,387,
158
+ 1,0,0,0,389,390,1,0,0,0,390,391,1,0,0,0,391,392,6,50,0,0,392,102,
159
+ 1,0,0,0,21,0,183,231,239,250,258,269,281,302,319,324,332,337,343,
160
+ 350,352,363,369,373,383,389,1,6,0,0
161
+ ]
162
+
163
+ class AutolevLexer(Lexer):
164
+
165
+ atn = ATNDeserializer().deserialize(serializedATN())
166
+
167
+ decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
168
+
169
+ T__0 = 1
170
+ T__1 = 2
171
+ T__2 = 3
172
+ T__3 = 4
173
+ T__4 = 5
174
+ T__5 = 6
175
+ T__6 = 7
176
+ T__7 = 8
177
+ T__8 = 9
178
+ T__9 = 10
179
+ T__10 = 11
180
+ T__11 = 12
181
+ T__12 = 13
182
+ T__13 = 14
183
+ T__14 = 15
184
+ T__15 = 16
185
+ T__16 = 17
186
+ T__17 = 18
187
+ T__18 = 19
188
+ T__19 = 20
189
+ T__20 = 21
190
+ T__21 = 22
191
+ T__22 = 23
192
+ T__23 = 24
193
+ T__24 = 25
194
+ T__25 = 26
195
+ Mass = 27
196
+ Inertia = 28
197
+ Input = 29
198
+ Output = 30
199
+ Save = 31
200
+ UnitSystem = 32
201
+ Encode = 33
202
+ Newtonian = 34
203
+ Frames = 35
204
+ Bodies = 36
205
+ Particles = 37
206
+ Points = 38
207
+ Constants = 39
208
+ Specifieds = 40
209
+ Imaginary = 41
210
+ Variables = 42
211
+ MotionVariables = 43
212
+ INT = 44
213
+ FLOAT = 45
214
+ EXP = 46
215
+ LINE_COMMENT = 47
216
+ ID = 48
217
+ WS = 49
218
+
219
+ channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
220
+
221
+ modeNames = [ "DEFAULT_MODE" ]
222
+
223
+ literalNames = [ "<INVALID>",
224
+ "'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='",
225
+ "'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'",
226
+ "'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
227
+
228
+ symbolicNames = [ "<INVALID>",
229
+ "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
230
+ "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points",
231
+ "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables",
232
+ "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ]
233
+
234
+ ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6",
235
+ "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13",
236
+ "T__14", "T__15", "T__16", "T__17", "T__18", "T__19",
237
+ "T__20", "T__21", "T__22", "T__23", "T__24", "T__25",
238
+ "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
239
+ "Encode", "Newtonian", "Frames", "Bodies", "Particles",
240
+ "Points", "Constants", "Specifieds", "Imaginary", "Variables",
241
+ "MotionVariables", "DIFF", "DIGIT", "INT", "FLOAT", "EXP",
242
+ "LINE_COMMENT", "ID", "WS" ]
243
+
244
+ grammarFileName = "Autolev.g4"
245
+
246
+ def __init__(self, input=None, output:TextIO = sys.stdout):
247
+ super().__init__(input, output)
248
+ self.checkVersion("4.11.1")
249
+ self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
250
+ self._actions = None
251
+ self._predicates = None
252
+
253
+
.venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
6
+ from antlr4 import *
7
+ if __name__ is not None and "." in __name__:
8
+ from .autolevparser import AutolevParser
9
+ else:
10
+ from autolevparser import AutolevParser
11
+
12
+ # This class defines a complete listener for a parse tree produced by AutolevParser.
13
+ class AutolevListener(ParseTreeListener):
14
+
15
+ # Enter a parse tree produced by AutolevParser#prog.
16
+ def enterProg(self, ctx:AutolevParser.ProgContext):
17
+ pass
18
+
19
+ # Exit a parse tree produced by AutolevParser#prog.
20
+ def exitProg(self, ctx:AutolevParser.ProgContext):
21
+ pass
22
+
23
+
24
+ # Enter a parse tree produced by AutolevParser#stat.
25
+ def enterStat(self, ctx:AutolevParser.StatContext):
26
+ pass
27
+
28
+ # Exit a parse tree produced by AutolevParser#stat.
29
+ def exitStat(self, ctx:AutolevParser.StatContext):
30
+ pass
31
+
32
+
33
+ # Enter a parse tree produced by AutolevParser#vecAssign.
34
+ def enterVecAssign(self, ctx:AutolevParser.VecAssignContext):
35
+ pass
36
+
37
+ # Exit a parse tree produced by AutolevParser#vecAssign.
38
+ def exitVecAssign(self, ctx:AutolevParser.VecAssignContext):
39
+ pass
40
+
41
+
42
+ # Enter a parse tree produced by AutolevParser#indexAssign.
43
+ def enterIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
44
+ pass
45
+
46
+ # Exit a parse tree produced by AutolevParser#indexAssign.
47
+ def exitIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
48
+ pass
49
+
50
+
51
+ # Enter a parse tree produced by AutolevParser#regularAssign.
52
+ def enterRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
53
+ pass
54
+
55
+ # Exit a parse tree produced by AutolevParser#regularAssign.
56
+ def exitRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
57
+ pass
58
+
59
+
60
+ # Enter a parse tree produced by AutolevParser#equals.
61
+ def enterEquals(self, ctx:AutolevParser.EqualsContext):
62
+ pass
63
+
64
+ # Exit a parse tree produced by AutolevParser#equals.
65
+ def exitEquals(self, ctx:AutolevParser.EqualsContext):
66
+ pass
67
+
68
+
69
+ # Enter a parse tree produced by AutolevParser#index.
70
+ def enterIndex(self, ctx:AutolevParser.IndexContext):
71
+ pass
72
+
73
+ # Exit a parse tree produced by AutolevParser#index.
74
+ def exitIndex(self, ctx:AutolevParser.IndexContext):
75
+ pass
76
+
77
+
78
+ # Enter a parse tree produced by AutolevParser#diff.
79
+ def enterDiff(self, ctx:AutolevParser.DiffContext):
80
+ pass
81
+
82
+ # Exit a parse tree produced by AutolevParser#diff.
83
+ def exitDiff(self, ctx:AutolevParser.DiffContext):
84
+ pass
85
+
86
+
87
+ # Enter a parse tree produced by AutolevParser#functionCall.
88
+ def enterFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
89
+ pass
90
+
91
+ # Exit a parse tree produced by AutolevParser#functionCall.
92
+ def exitFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
93
+ pass
94
+
95
+
96
+ # Enter a parse tree produced by AutolevParser#varDecl.
97
+ def enterVarDecl(self, ctx:AutolevParser.VarDeclContext):
98
+ pass
99
+
100
+ # Exit a parse tree produced by AutolevParser#varDecl.
101
+ def exitVarDecl(self, ctx:AutolevParser.VarDeclContext):
102
+ pass
103
+
104
+
105
+ # Enter a parse tree produced by AutolevParser#varType.
106
+ def enterVarType(self, ctx:AutolevParser.VarTypeContext):
107
+ pass
108
+
109
+ # Exit a parse tree produced by AutolevParser#varType.
110
+ def exitVarType(self, ctx:AutolevParser.VarTypeContext):
111
+ pass
112
+
113
+
114
+ # Enter a parse tree produced by AutolevParser#varDecl2.
115
+ def enterVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
116
+ pass
117
+
118
+ # Exit a parse tree produced by AutolevParser#varDecl2.
119
+ def exitVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
120
+ pass
121
+
122
+
123
+ # Enter a parse tree produced by AutolevParser#ranges.
124
+ def enterRanges(self, ctx:AutolevParser.RangesContext):
125
+ pass
126
+
127
+ # Exit a parse tree produced by AutolevParser#ranges.
128
+ def exitRanges(self, ctx:AutolevParser.RangesContext):
129
+ pass
130
+
131
+
132
+ # Enter a parse tree produced by AutolevParser#massDecl.
133
+ def enterMassDecl(self, ctx:AutolevParser.MassDeclContext):
134
+ pass
135
+
136
+ # Exit a parse tree produced by AutolevParser#massDecl.
137
+ def exitMassDecl(self, ctx:AutolevParser.MassDeclContext):
138
+ pass
139
+
140
+
141
+ # Enter a parse tree produced by AutolevParser#massDecl2.
142
+ def enterMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
143
+ pass
144
+
145
+ # Exit a parse tree produced by AutolevParser#massDecl2.
146
+ def exitMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
147
+ pass
148
+
149
+
150
+ # Enter a parse tree produced by AutolevParser#inertiaDecl.
151
+ def enterInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
152
+ pass
153
+
154
+ # Exit a parse tree produced by AutolevParser#inertiaDecl.
155
+ def exitInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
156
+ pass
157
+
158
+
159
+ # Enter a parse tree produced by AutolevParser#matrix.
160
+ def enterMatrix(self, ctx:AutolevParser.MatrixContext):
161
+ pass
162
+
163
+ # Exit a parse tree produced by AutolevParser#matrix.
164
+ def exitMatrix(self, ctx:AutolevParser.MatrixContext):
165
+ pass
166
+
167
+
168
+ # Enter a parse tree produced by AutolevParser#matrixInOutput.
169
+ def enterMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
170
+ pass
171
+
172
+ # Exit a parse tree produced by AutolevParser#matrixInOutput.
173
+ def exitMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
174
+ pass
175
+
176
+
177
+ # Enter a parse tree produced by AutolevParser#codeCommands.
178
+ def enterCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
179
+ pass
180
+
181
+ # Exit a parse tree produced by AutolevParser#codeCommands.
182
+ def exitCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
183
+ pass
184
+
185
+
186
+ # Enter a parse tree produced by AutolevParser#settings.
187
+ def enterSettings(self, ctx:AutolevParser.SettingsContext):
188
+ pass
189
+
190
+ # Exit a parse tree produced by AutolevParser#settings.
191
+ def exitSettings(self, ctx:AutolevParser.SettingsContext):
192
+ pass
193
+
194
+
195
+ # Enter a parse tree produced by AutolevParser#units.
196
+ def enterUnits(self, ctx:AutolevParser.UnitsContext):
197
+ pass
198
+
199
+ # Exit a parse tree produced by AutolevParser#units.
200
+ def exitUnits(self, ctx:AutolevParser.UnitsContext):
201
+ pass
202
+
203
+
204
+ # Enter a parse tree produced by AutolevParser#inputs.
205
+ def enterInputs(self, ctx:AutolevParser.InputsContext):
206
+ pass
207
+
208
+ # Exit a parse tree produced by AutolevParser#inputs.
209
+ def exitInputs(self, ctx:AutolevParser.InputsContext):
210
+ pass
211
+
212
+
213
+ # Enter a parse tree produced by AutolevParser#id_diff.
214
+ def enterId_diff(self, ctx:AutolevParser.Id_diffContext):
215
+ pass
216
+
217
+ # Exit a parse tree produced by AutolevParser#id_diff.
218
+ def exitId_diff(self, ctx:AutolevParser.Id_diffContext):
219
+ pass
220
+
221
+
222
+ # Enter a parse tree produced by AutolevParser#inputs2.
223
+ def enterInputs2(self, ctx:AutolevParser.Inputs2Context):
224
+ pass
225
+
226
+ # Exit a parse tree produced by AutolevParser#inputs2.
227
+ def exitInputs2(self, ctx:AutolevParser.Inputs2Context):
228
+ pass
229
+
230
+
231
+ # Enter a parse tree produced by AutolevParser#outputs.
232
+ def enterOutputs(self, ctx:AutolevParser.OutputsContext):
233
+ pass
234
+
235
+ # Exit a parse tree produced by AutolevParser#outputs.
236
+ def exitOutputs(self, ctx:AutolevParser.OutputsContext):
237
+ pass
238
+
239
+
240
+ # Enter a parse tree produced by AutolevParser#outputs2.
241
+ def enterOutputs2(self, ctx:AutolevParser.Outputs2Context):
242
+ pass
243
+
244
+ # Exit a parse tree produced by AutolevParser#outputs2.
245
+ def exitOutputs2(self, ctx:AutolevParser.Outputs2Context):
246
+ pass
247
+
248
+
249
+ # Enter a parse tree produced by AutolevParser#codegen.
250
+ def enterCodegen(self, ctx:AutolevParser.CodegenContext):
251
+ pass
252
+
253
+ # Exit a parse tree produced by AutolevParser#codegen.
254
+ def exitCodegen(self, ctx:AutolevParser.CodegenContext):
255
+ pass
256
+
257
+
258
+ # Enter a parse tree produced by AutolevParser#commands.
259
+ def enterCommands(self, ctx:AutolevParser.CommandsContext):
260
+ pass
261
+
262
+ # Exit a parse tree produced by AutolevParser#commands.
263
+ def exitCommands(self, ctx:AutolevParser.CommandsContext):
264
+ pass
265
+
266
+
267
+ # Enter a parse tree produced by AutolevParser#vec.
268
+ def enterVec(self, ctx:AutolevParser.VecContext):
269
+ pass
270
+
271
+ # Exit a parse tree produced by AutolevParser#vec.
272
+ def exitVec(self, ctx:AutolevParser.VecContext):
273
+ pass
274
+
275
+
276
+ # Enter a parse tree produced by AutolevParser#parens.
277
+ def enterParens(self, ctx:AutolevParser.ParensContext):
278
+ pass
279
+
280
+ # Exit a parse tree produced by AutolevParser#parens.
281
+ def exitParens(self, ctx:AutolevParser.ParensContext):
282
+ pass
283
+
284
+
285
+ # Enter a parse tree produced by AutolevParser#VectorOrDyadic.
286
+ def enterVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
287
+ pass
288
+
289
+ # Exit a parse tree produced by AutolevParser#VectorOrDyadic.
290
+ def exitVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
291
+ pass
292
+
293
+
294
+ # Enter a parse tree produced by AutolevParser#Exponent.
295
+ def enterExponent(self, ctx:AutolevParser.ExponentContext):
296
+ pass
297
+
298
+ # Exit a parse tree produced by AutolevParser#Exponent.
299
+ def exitExponent(self, ctx:AutolevParser.ExponentContext):
300
+ pass
301
+
302
+
303
+ # Enter a parse tree produced by AutolevParser#MulDiv.
304
+ def enterMulDiv(self, ctx:AutolevParser.MulDivContext):
305
+ pass
306
+
307
+ # Exit a parse tree produced by AutolevParser#MulDiv.
308
+ def exitMulDiv(self, ctx:AutolevParser.MulDivContext):
309
+ pass
310
+
311
+
312
+ # Enter a parse tree produced by AutolevParser#AddSub.
313
+ def enterAddSub(self, ctx:AutolevParser.AddSubContext):
314
+ pass
315
+
316
+ # Exit a parse tree produced by AutolevParser#AddSub.
317
+ def exitAddSub(self, ctx:AutolevParser.AddSubContext):
318
+ pass
319
+
320
+
321
+ # Enter a parse tree produced by AutolevParser#float.
322
+ def enterFloat(self, ctx:AutolevParser.FloatContext):
323
+ pass
324
+
325
+ # Exit a parse tree produced by AutolevParser#float.
326
+ def exitFloat(self, ctx:AutolevParser.FloatContext):
327
+ pass
328
+
329
+
330
+ # Enter a parse tree produced by AutolevParser#int.
331
+ def enterInt(self, ctx:AutolevParser.IntContext):
332
+ pass
333
+
334
+ # Exit a parse tree produced by AutolevParser#int.
335
+ def exitInt(self, ctx:AutolevParser.IntContext):
336
+ pass
337
+
338
+
339
+ # Enter a parse tree produced by AutolevParser#idEqualsExpr.
340
+ def enterIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
341
+ pass
342
+
343
+ # Exit a parse tree produced by AutolevParser#idEqualsExpr.
344
+ def exitIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
345
+ pass
346
+
347
+
348
+ # Enter a parse tree produced by AutolevParser#negativeOne.
349
+ def enterNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
350
+ pass
351
+
352
+ # Exit a parse tree produced by AutolevParser#negativeOne.
353
+ def exitNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
354
+ pass
355
+
356
+
357
+ # Enter a parse tree produced by AutolevParser#function.
358
+ def enterFunction(self, ctx:AutolevParser.FunctionContext):
359
+ pass
360
+
361
+ # Exit a parse tree produced by AutolevParser#function.
362
+ def exitFunction(self, ctx:AutolevParser.FunctionContext):
363
+ pass
364
+
365
+
366
+ # Enter a parse tree produced by AutolevParser#rangess.
367
+ def enterRangess(self, ctx:AutolevParser.RangessContext):
368
+ pass
369
+
370
+ # Exit a parse tree produced by AutolevParser#rangess.
371
+ def exitRangess(self, ctx:AutolevParser.RangessContext):
372
+ pass
373
+
374
+
375
+ # Enter a parse tree produced by AutolevParser#colon.
376
+ def enterColon(self, ctx:AutolevParser.ColonContext):
377
+ pass
378
+
379
+ # Exit a parse tree produced by AutolevParser#colon.
380
+ def exitColon(self, ctx:AutolevParser.ColonContext):
381
+ pass
382
+
383
+
384
+ # Enter a parse tree produced by AutolevParser#id.
385
+ def enterId(self, ctx:AutolevParser.IdContext):
386
+ pass
387
+
388
+ # Exit a parse tree produced by AutolevParser#id.
389
+ def exitId(self, ctx:AutolevParser.IdContext):
390
+ pass
391
+
392
+
393
+ # Enter a parse tree produced by AutolevParser#exp.
394
+ def enterExp(self, ctx:AutolevParser.ExpContext):
395
+ pass
396
+
397
+ # Exit a parse tree produced by AutolevParser#exp.
398
+ def exitExp(self, ctx:AutolevParser.ExpContext):
399
+ pass
400
+
401
+
402
+ # Enter a parse tree produced by AutolevParser#matrices.
403
+ def enterMatrices(self, ctx:AutolevParser.MatricesContext):
404
+ pass
405
+
406
+ # Exit a parse tree produced by AutolevParser#matrices.
407
+ def exitMatrices(self, ctx:AutolevParser.MatricesContext):
408
+ pass
409
+
410
+
411
+ # Enter a parse tree produced by AutolevParser#Indexing.
412
+ def enterIndexing(self, ctx:AutolevParser.IndexingContext):
413
+ pass
414
+
415
+ # Exit a parse tree produced by AutolevParser#Indexing.
416
+ def exitIndexing(self, ctx:AutolevParser.IndexingContext):
417
+ pass
418
+
419
+
420
+
421
+ del AutolevParser
.venv/Lib/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/Lib/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import glob
4
+
5
+ from sympy.utilities.misc import debug
6
+
7
+ here = os.path.dirname(__file__)
8
+ grammar_file = os.path.abspath(os.path.join(here, "Autolev.g4"))
9
+ dir_autolev_antlr = os.path.join(here, "_antlr")
10
+
11
+ header = '''\
12
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
13
+ #
14
+ # Generated with antlr4
15
+ # antlr4 is licensed under the BSD-3-Clause License
16
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
17
+ '''
18
+
19
+
20
+ def check_antlr_version():
21
+ debug("Checking antlr4 version...")
22
+
23
+ try:
24
+ debug(subprocess.check_output(["antlr4"])
25
+ .decode('utf-8').split("\n")[0])
26
+ return True
27
+ except (subprocess.CalledProcessError, FileNotFoundError):
28
+ debug("The 'antlr4' command line tool is not installed, "
29
+ "or not on your PATH.\n"
30
+ "> Please refer to the README.md file for more information.")
31
+ return False
32
+
33
+
34
+ def build_parser(output_dir=dir_autolev_antlr):
35
+ check_antlr_version()
36
+
37
+ debug("Updating ANTLR-generated code in {}".format(output_dir))
38
+
39
+ if not os.path.exists(output_dir):
40
+ os.makedirs(output_dir)
41
+
42
+ with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
43
+ fp.write(header)
44
+
45
+ args = [
46
+ "antlr4",
47
+ grammar_file,
48
+ "-o", output_dir,
49
+ "-no-visitor",
50
+ ]
51
+
52
+ debug("Running code generation...\n\t$ {}".format(" ".join(args)))
53
+ subprocess.check_output(args, cwd=output_dir)
54
+
55
+ debug("Applying headers, removing unnecessary files and renaming...")
56
+ # Handle case insensitive file systems. If the files are already
57
+ # generated, they will be written to autolev* but Autolev*.* won't match them.
58
+ for path in (glob.glob(os.path.join(output_dir, "Autolev*.*")) or
59
+ glob.glob(os.path.join(output_dir, "autolev*.*"))):
60
+
61
+ # Remove files ending in .interp or .tokens as they are not needed.
62
+ if not path.endswith(".py"):
63
+ os.unlink(path)
64
+ continue
65
+
66
+ new_path = os.path.join(output_dir, os.path.basename(path).lower())
67
+ with open(path, 'r') as f:
68
+ lines = [line.rstrip().replace('AutolevParser import', 'autolevparser import') +'\n'
69
+ for line in f]
70
+
71
+ os.unlink(path)
72
+
73
+ with open(new_path, "w") as out_file:
74
+ offset = 0
75
+ while lines[offset].startswith('#'):
76
+ offset += 1
77
+ out_file.write(header)
78
+ out_file.writelines(lines[offset:])
79
+
80
+ debug("\t{}".format(new_path))
81
+
82
+ return True
83
+
84
+
85
+ if __name__ == "__main__":
86
+ build_parser()
.venv/Lib/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/Lib/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from importlib.metadata import version
2
+ from sympy.external import import_module
3
+
4
+
5
+ autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
6
+ import_kwargs={'fromlist': ['AutolevParser']})
7
+ autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
8
+ import_kwargs={'fromlist': ['AutolevLexer']})
9
+ autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
10
+ import_kwargs={'fromlist': ['AutolevListener']})
11
+
12
+ AutolevParser = getattr(autolevparser, 'AutolevParser', None)
13
+ AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
14
+ AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
15
+
16
+
17
+ def parse_autolev(autolev_code, include_numeric):
18
+ antlr4 = import_module('antlr4')
19
+ if not antlr4 or not version('antlr4-python3-runtime').startswith('4.11'):
20
+ raise ImportError("Autolev parsing requires the antlr4 Python package,"
21
+ " provided by pip (antlr4-python3-runtime)"
22
+ " conda (antlr-python-runtime), version 4.11")
23
+ try:
24
+ l = autolev_code.readlines()
25
+ input_stream = antlr4.InputStream("".join(l))
26
+ except Exception:
27
+ input_stream = antlr4.InputStream(autolev_code)
28
+
29
+ if AutolevListener:
30
+ from ._listener_autolev_antlr import MyListener
31
+ lexer = AutolevLexer(input_stream)
32
+ token_stream = antlr4.CommonTokenStream(lexer)
33
+ parser = AutolevParser(token_stream)
34
+ tree = parser.prog()
35
+ my_listener = MyListener(include_numeric)
36
+ walker = antlr4.ParseTreeWalker()
37
+ walker.walk(my_listener, tree)
38
+ return "".join(my_listener.output_code)
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/README.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # parsing/tests/test_autolev.py uses the .al files in this directory as inputs and checks
2
+ # the equivalence of the parser generated codes and the respective .py files.
3
+
4
+ # By default, this directory contains tests for all rules of the parser.
5
+
6
+ # Additional tests consisting of full physics examples shall be made available soon in
7
+ # the form of another repository. One shall be able to copy the contents of that repo
8
+ # to this folder and use those tests after uncommenting the respective code in
9
+ # parsing/tests/test_autolev.py.
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONSTANTS G,LB,W,H
2
+ MOTIONVARIABLES' THETA'',PHI'',OMEGA',ALPHA'
3
+ NEWTONIAN N
4
+ BODIES A,B
5
+ SIMPROT(N,A,2,THETA)
6
+ SIMPROT(A,B,3,PHI)
7
+ POINT O
8
+ LA = (LB-H/2)/2
9
+ P_O_AO> = LA*A3>
10
+ P_O_BO> = LB*A3>
11
+ OMEGA = THETA'
12
+ ALPHA = PHI'
13
+ W_A_N> = OMEGA*N2>
14
+ W_B_A> = ALPHA*A3>
15
+ V_O_N> = 0>
16
+ V2PTS(N, A, O, AO)
17
+ V2PTS(N, A, O, BO)
18
+ MASS A=MA, B=MB
19
+ IAXX = 1/12*MA*(2*LA)^2
20
+ IAYY = IAXX
21
+ IAZZ = 0
22
+ IBXX = 1/12*MB*H^2
23
+ IBYY = 1/12*MB*(W^2+H^2)
24
+ IBZZ = 1/12*MB*W^2
25
+ INERTIA A, IAXX, IAYY, IAZZ
26
+ INERTIA B, IBXX, IBYY, IBZZ
27
+ GRAVITY(G*N3>)
28
+ ZERO = FR() + FRSTAR()
29
+ KANE()
30
+ INPUT LB=0.2,H=0.1,W=0.2,MA=0.01,MB=0.1,G=9.81
31
+ INPUT THETA = 90 DEG, PHI = 0.5 DEG, OMEGA=0, ALPHA=0
32
+ INPUT TFINAL=10, INTEGSTP=0.02
33
+ CODE DYNAMICS() some_filename.c
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ g, lb, w, h = _sm.symbols('g lb w h', real=True)
7
+ theta, phi, omega, alpha = _me.dynamicsymbols('theta phi omega alpha')
8
+ theta_d, phi_d, omega_d, alpha_d = _me.dynamicsymbols('theta_ phi_ omega_ alpha_', 1)
9
+ theta_dd, phi_dd = _me.dynamicsymbols('theta_ phi_', 2)
10
+ frame_n = _me.ReferenceFrame('n')
11
+ body_a_cm = _me.Point('a_cm')
12
+ body_a_cm.set_vel(frame_n, 0)
13
+ body_a_f = _me.ReferenceFrame('a_f')
14
+ body_a = _me.RigidBody('a', body_a_cm, body_a_f, _sm.symbols('m'), (_me.outer(body_a_f.x,body_a_f.x),body_a_cm))
15
+ body_b_cm = _me.Point('b_cm')
16
+ body_b_cm.set_vel(frame_n, 0)
17
+ body_b_f = _me.ReferenceFrame('b_f')
18
+ body_b = _me.RigidBody('b', body_b_cm, body_b_f, _sm.symbols('m'), (_me.outer(body_b_f.x,body_b_f.x),body_b_cm))
19
+ body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])
20
+ body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])
21
+ point_o = _me.Point('o')
22
+ la = (lb-h/2)/2
23
+ body_a_cm.set_pos(point_o, la*body_a_f.z)
24
+ body_b_cm.set_pos(point_o, lb*body_a_f.z)
25
+ body_a_f.set_ang_vel(frame_n, omega*frame_n.y)
26
+ body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)
27
+ point_o.set_vel(frame_n, 0)
28
+ body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)
29
+ body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)
30
+ ma = _sm.symbols('ma')
31
+ body_a.mass = ma
32
+ mb = _sm.symbols('mb')
33
+ body_b.mass = mb
34
+ iaxx = 1/12*ma*(2*la)**2
35
+ iayy = iaxx
36
+ iazz = 0
37
+ ibxx = 1/12*mb*h**2
38
+ ibyy = 1/12*mb*(w**2+h**2)
39
+ ibzz = 1/12*mb*w**2
40
+ body_a.inertia = (_me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)
41
+ body_b.inertia = (_me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)
42
+ force_a = body_a.mass*(g*frame_n.z)
43
+ force_b = body_b.mass*(g*frame_n.z)
44
+ kd_eqs = [theta_d - omega, phi_d - alpha]
45
+ forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]
46
+ kane = _me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)
47
+ fr, frstar = kane.kanes_equations([body_a, body_b], forceList)
48
+ zero = fr+frstar
49
+ from pydy.system import System
50
+ sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},
51
+ specifieds={},
52
+ initial_conditions={theta:_np.deg2rad(90), phi:_np.deg2rad(0.5), omega:0, alpha:0},
53
+ times = _np.linspace(0.0, 10, 10/0.02))
54
+
55
+ y=sys.integrate()
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MOTIONVARIABLES' Q{2}', U{2}'
2
+ CONSTANTS L,M,G
3
+ NEWTONIAN N
4
+ FRAMES A,B
5
+ SIMPROT(N, A, 3, Q1)
6
+ SIMPROT(N, B, 3, Q2)
7
+ W_A_N>=U1*N3>
8
+ W_B_N>=U2*N3>
9
+ POINT O
10
+ PARTICLES P,R
11
+ P_O_P> = L*A1>
12
+ P_P_R> = L*B1>
13
+ V_O_N> = 0>
14
+ V2PTS(N, A, O, P)
15
+ V2PTS(N, B, P, R)
16
+ MASS P=M, R=M
17
+ Q1' = U1
18
+ Q2' = U2
19
+ GRAVITY(G*N1>)
20
+ ZERO = FR() + FRSTAR()
21
+ KANE()
22
+ INPUT M=1,G=9.81,L=1
23
+ INPUT Q1=.1,Q2=.2,U1=0,U2=0
24
+ INPUT TFINAL=10, INTEGSTP=.01
25
+ CODE DYNAMICS() some_filename.c
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
7
+ q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
8
+ l, m, g = _sm.symbols('l m g', real=True)
9
+ frame_n = _me.ReferenceFrame('n')
10
+ frame_a = _me.ReferenceFrame('a')
11
+ frame_b = _me.ReferenceFrame('b')
12
+ frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
13
+ frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
14
+ frame_a.set_ang_vel(frame_n, u1*frame_n.z)
15
+ frame_b.set_ang_vel(frame_n, u2*frame_n.z)
16
+ point_o = _me.Point('o')
17
+ particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
18
+ particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
19
+ particle_p.point.set_pos(point_o, l*frame_a.x)
20
+ particle_r.point.set_pos(particle_p.point, l*frame_b.x)
21
+ point_o.set_vel(frame_n, 0)
22
+ particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
23
+ particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
24
+ particle_p.mass = m
25
+ particle_r.mass = m
26
+ force_p = particle_p.mass*(g*frame_n.x)
27
+ force_r = particle_r.mass*(g*frame_n.x)
28
+ kd_eqs = [q1_d - u1, q2_d - u2]
29
+ forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
30
+ kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
31
+ fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
32
+ zero = fr+frstar
33
+ from pydy.system import System
34
+ sys = System(kane, constants = {l:1, m:1, g:9.81},
35
+ specifieds={},
36
+ initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
37
+ times = _np.linspace(0.0, 10, 10/.01))
38
+
39
+ y=sys.integrate()
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONSTANTS M,K,B,G
2
+ MOTIONVARIABLES' POSITION',SPEED'
3
+ VARIABLES O
4
+ FORCE = O*SIN(T)
5
+ NEWTONIAN CEILING
6
+ POINTS ORIGIN
7
+ V_ORIGIN_CEILING> = 0>
8
+ PARTICLES BLOCK
9
+ P_ORIGIN_BLOCK> = POSITION*CEILING1>
10
+ MASS BLOCK=M
11
+ V_BLOCK_CEILING>=SPEED*CEILING1>
12
+ POSITION' = SPEED
13
+ FORCE_MAGNITUDE = M*G-K*POSITION-B*SPEED+FORCE
14
+ FORCE_BLOCK>=EXPLICIT(FORCE_MAGNITUDE*CEILING1>)
15
+ ZERO = FR() + FRSTAR()
16
+ KANE()
17
+ INPUT TFINAL=10.0, INTEGSTP=0.01
18
+ INPUT M=1.0, K=1.0, B=0.2, G=9.8, POSITION=0.1, SPEED=-1.0, O=2
19
+ CODE DYNAMICS() dummy_file.c
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ m, k, b, g = _sm.symbols('m k b g', real=True)
7
+ position, speed = _me.dynamicsymbols('position speed')
8
+ position_d, speed_d = _me.dynamicsymbols('position_ speed_', 1)
9
+ o = _me.dynamicsymbols('o')
10
+ force = o*_sm.sin(_me.dynamicsymbols._t)
11
+ frame_ceiling = _me.ReferenceFrame('ceiling')
12
+ point_origin = _me.Point('origin')
13
+ point_origin.set_vel(frame_ceiling, 0)
14
+ particle_block = _me.Particle('block', _me.Point('block_pt'), _sm.Symbol('m'))
15
+ particle_block.point.set_pos(point_origin, position*frame_ceiling.x)
16
+ particle_block.mass = m
17
+ particle_block.point.set_vel(frame_ceiling, speed*frame_ceiling.x)
18
+ force_magnitude = m*g-k*position-b*speed+force
19
+ force_block = (force_magnitude*frame_ceiling.x).subs({position_d:speed})
20
+ kd_eqs = [position_d - speed]
21
+ forceList = [(particle_block.point,(force_magnitude*frame_ceiling.x).subs({position_d:speed}))]
22
+ kane = _me.KanesMethod(frame_ceiling, q_ind=[position], u_ind=[speed], kd_eqs = kd_eqs)
23
+ fr, frstar = kane.kanes_equations([particle_block], forceList)
24
+ zero = fr+frstar
25
+ from pydy.system import System
26
+ sys = System(kane, constants = {m:1.0, k:1.0, b:0.2, g:9.8},
27
+ specifieds={_me.dynamicsymbols('t'):lambda x, t: t, o:2},
28
+ initial_conditions={position:0.1, speed:-1*1.0},
29
+ times = _np.linspace(0.0, 10.0, 10.0/0.01))
30
+
31
+ y=sys.integrate()
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MOTIONVARIABLES' Q{2}''
2
+ CONSTANTS L,M,G
3
+ NEWTONIAN N
4
+ POINT PN
5
+ V_PN_N> = 0>
6
+ THETA1 = ATAN(Q2/Q1)
7
+ FRAMES A
8
+ SIMPROT(N, A, 3, THETA1)
9
+ PARTICLES P
10
+ P_PN_P> = Q1*N1>+Q2*N2>
11
+ MASS P=M
12
+ V_P_N>=DT(P_P_PN>, N)
13
+ F_V = DOT(EXPRESS(V_P_N>,A), A1>)
14
+ GRAVITY(G*N1>)
15
+ DEPENDENT[1] = F_V
16
+ CONSTRAIN(DEPENDENT[Q1'])
17
+ ZERO=FR()+FRSTAR()
18
+ F_C = MAG(P_P_PN>)-L
19
+ CONFIG[1]=F_C
20
+ ZERO[2]=CONFIG[1]
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ q1, q2 = _me.dynamicsymbols('q1 q2')
7
+ q1_d, q2_d = _me.dynamicsymbols('q1_ q2_', 1)
8
+ q1_dd, q2_dd = _me.dynamicsymbols('q1_ q2_', 2)
9
+ l, m, g = _sm.symbols('l m g', real=True)
10
+ frame_n = _me.ReferenceFrame('n')
11
+ point_pn = _me.Point('pn')
12
+ point_pn.set_vel(frame_n, 0)
13
+ theta1 = _sm.atan(q2/q1)
14
+ frame_a = _me.ReferenceFrame('a')
15
+ frame_a.orient(frame_n, 'Axis', [theta1, frame_n.z])
16
+ particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
17
+ particle_p.point.set_pos(point_pn, q1*frame_n.x+q2*frame_n.y)
18
+ particle_p.mass = m
19
+ particle_p.point.set_vel(frame_n, (point_pn.pos_from(particle_p.point)).dt(frame_n))
20
+ f_v = _me.dot((particle_p.point.vel(frame_n)).express(frame_a), frame_a.x)
21
+ force_p = particle_p.mass*(g*frame_n.x)
22
+ dependent = _sm.Matrix([[0]])
23
+ dependent[0] = f_v
24
+ velocity_constraints = [i for i in dependent]
25
+ u_q1_d = _me.dynamicsymbols('u_q1_d')
26
+ u_q2_d = _me.dynamicsymbols('u_q2_d')
27
+ kd_eqs = [q1_d-u_q1_d, q2_d-u_q2_d]
28
+ forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x))]
29
+ kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u_q2_d], u_dependent=[u_q1_d], kd_eqs = kd_eqs, velocity_constraints = velocity_constraints)
30
+ fr, frstar = kane.kanes_equations([particle_p], forceList)
31
+ zero = fr+frstar
32
+ f_c = point_pn.pos_from(particle_p.point).magnitude()-l
33
+ config = _sm.Matrix([[0]])
34
+ config[0] = f_c
35
+ zero = zero.row_insert(zero.shape[0], _sm.Matrix([[0]]))
36
+ zero[zero.shape[0]-1] = config[0]
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest1.al ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ % ruletest1.al
2
+ CONSTANTS F = 3, G = 9.81
3
+ CONSTANTS A, B
4
+ CONSTANTS S, S1, S2+, S3+, S4-
5
+ CONSTANTS K{4}, L{1:3}, P{1:2,1:3}
6
+ CONSTANTS C{2,3}
7
+ E1 = A*F + S2 - G
8
+ E2 = F^2 + K3*K2*G
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ f = _sm.S(3)
7
+ g = _sm.S(9.81)
8
+ a, b = _sm.symbols('a b', real=True)
9
+ s, s1 = _sm.symbols('s s1', real=True)
10
+ s2, s3 = _sm.symbols('s2 s3', real=True, nonnegative=True)
11
+ s4 = _sm.symbols('s4', real=True, nonpositive=True)
12
+ k1, k2, k3, k4, l1, l2, l3, p11, p12, p13, p21, p22, p23 = _sm.symbols('k1 k2 k3 k4 l1 l2 l3 p11 p12 p13 p21 p22 p23', real=True)
13
+ c11, c12, c13, c21, c22, c23 = _sm.symbols('c11 c12 c13 c21 c22 c23', real=True)
14
+ e1 = a*f+s2-g
15
+ e2 = f**2+k3*k2*g
.venv/Lib/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % ruletest10.al
2
+
3
+ VARIABLES X,Y
4
+ COMPLEX ON
5
+ CONSTANTS A,B
6
+ E = A*(B*X+Y)^2
7
+ M = [E;E]
8
+ EXPAND(E)
9
+ EXPAND(M)
10
+ FACTOR(E,X)
11
+ FACTOR(M,X)
12
+
13
+ EQN[1] = A*X + B*Y
14
+ EQN[2] = 2*A*X - 3*B*Y
15
+ SOLVE(EQN, X, Y)
16
+ RHS_Y = RHS(Y)
17
+ E = (X+Y)^2 + 2*X^2
18
+ ARRANGE(E, 2, X)
19
+
20
+ CONSTANTS A,B,C
21
+ M = [A,B;C,0]
22
+ M2 = EVALUATE(M,A=1,B=2,C=3)
23
+ EIG(M2, EIGVALUE, EIGVEC)
24
+
25
+ NEWTONIAN N
26
+ FRAMES A
27
+ SIMPROT(N, A, N1>, X)
28
+ DEGREES OFF
29
+ SIMPROT(N, A, N1>, PI/2)
30
+
31
+ CONSTANTS C{3}
32
+ V> = C1*A1> + C2*A2> + C3*A3>
33
+ POINTS O, P
34
+ P_P_O> = C1*A1>
35
+ EXPRESS(V>,N)
36
+ EXPRESS(P_P_O>,N)
37
+ W_A_N> = C3*A3>
38
+ ANGVEL(A,N)
39
+
40
+ V2PTS(N,A,O,P)
41
+ PARTICLES P{2}
42
+ V2PTS(N,A,P1,P2)
43
+ A2PTS(N,A,P1,P)
44
+
45
+ BODIES B{2}
46
+ CONSTANT G
47
+ GRAVITY(G*N1>)
48
+
49
+ VARIABLE Z
50
+ V> = X*A1> + Y*A3>
51
+ P_P_O> = X*A1> + Y*A2>
52
+ X = 2*Z
53
+ Y = Z
54
+ EXPLICIT(V>)
55
+ EXPLICIT(P_P_O>)
56
+
57
+ FORCE(O/P1, X*Y*A1>)
58
+ FORCE(P2, X*Y*A1>)