primetest.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. """
  2. Primality testing
  3. """
  4. from sympy.core.numbers import igcd
  5. from sympy.core.power import integer_nthroot
  6. from sympy.core.sympify import sympify
  7. from sympy.external.gmpy import HAS_GMPY
  8. from sympy.utilities.misc import as_int
  9. from mpmath.libmp import bitcount as _bitlength
  10. def _int_tuple(*i):
  11. return tuple(int(_) for _ in i)
  12. def is_euler_pseudoprime(n, b):
  13. """Returns True if n is prime or an Euler pseudoprime to base b, else False.
  14. Euler Pseudoprime : In arithmetic, an odd composite integer n is called an
  15. euler pseudoprime to base a, if a and n are coprime and satisfy the modular
  16. arithmetic congruence relation :
  17. a ^ (n-1)/2 = + 1(mod n) or
  18. a ^ (n-1)/2 = - 1(mod n)
  19. (where mod refers to the modulo operation).
  20. Examples
  21. ========
  22. >>> from sympy.ntheory.primetest import is_euler_pseudoprime
  23. >>> is_euler_pseudoprime(2, 5)
  24. True
  25. References
  26. ==========
  27. .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
  28. """
  29. from sympy.ntheory.factor_ import trailing
  30. if not mr(n, [b]):
  31. return False
  32. n = as_int(n)
  33. r = n - 1
  34. c = pow(b, r >> trailing(r), n)
  35. if c == 1:
  36. return True
  37. while True:
  38. if c == n - 1:
  39. return True
  40. c = pow(c, 2, n)
  41. if c == 1:
  42. return False
  43. def is_square(n, prep=True):
  44. """Return True if n == a * a for some integer a, else False.
  45. If n is suspected of *not* being a square then this is a
  46. quick method of confirming that it is not.
  47. Examples
  48. ========
  49. >>> from sympy.ntheory.primetest import is_square
  50. >>> is_square(25)
  51. True
  52. >>> is_square(2)
  53. False
  54. References
  55. ==========
  56. .. [1] http://mersenneforum.org/showpost.php?p=110896
  57. See Also
  58. ========
  59. sympy.core.power.integer_nthroot
  60. """
  61. if prep:
  62. n = as_int(n)
  63. if n < 0:
  64. return False
  65. if n in (0, 1):
  66. return True
  67. # def magic(n):
  68. # s = {x**2 % n for x in range(n)}
  69. # return sum(1 << bit for bit in s)
  70. # >>> print(hex(magic(128)))
  71. # 0x2020212020202130202021202030213
  72. # >>> print(hex(magic(99)))
  73. # 0x209060049048220348a410213
  74. # >>> print(hex(magic(91)))
  75. # 0x102e403012a0c9862c14213
  76. # >>> print(hex(magic(85)))
  77. # 0x121065188e001c46298213
  78. if not 0x2020212020202130202021202030213 & (1 << (n & 127)):
  79. return False
  80. m = n % (99 * 91 * 85)
  81. if not 0x209060049048220348a410213 & (1 << (m % 99)):
  82. return False
  83. if not 0x102e403012a0c9862c14213 & (1 << (m % 91)):
  84. return False
  85. if not 0x121065188e001c46298213 & (1 << (m % 85)):
  86. return False
  87. return integer_nthroot(n, 2)[1]
  88. def _test(n, base, s, t):
  89. """Miller-Rabin strong pseudoprime test for one base.
  90. Return False if n is definitely composite, True if n is
  91. probably prime, with a probability greater than 3/4.
  92. """
  93. # do the Fermat test
  94. b = pow(base, t, n)
  95. if b == 1 or b == n - 1:
  96. return True
  97. else:
  98. for j in range(1, s):
  99. b = pow(b, 2, n)
  100. if b == n - 1:
  101. return True
  102. # see I. Niven et al. "An Introduction to Theory of Numbers", page 78
  103. if b == 1:
  104. return False
  105. return False
  106. def mr(n, bases):
  107. """Perform a Miller-Rabin strong pseudoprime test on n using a
  108. given list of bases/witnesses.
  109. References
  110. ==========
  111. .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
  112. A Computational Perspective", Springer, 2nd edition, 135-138
  113. A list of thresholds and the bases they require are here:
  114. https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
  115. Examples
  116. ========
  117. >>> from sympy.ntheory.primetest import mr
  118. >>> mr(1373651, [2, 3])
  119. False
  120. >>> mr(479001599, [31, 73])
  121. True
  122. """
  123. from sympy.ntheory.factor_ import trailing
  124. from sympy.polys.domains import ZZ
  125. n = as_int(n)
  126. if n < 2:
  127. return False
  128. # remove powers of 2 from n-1 (= t * 2**s)
  129. s = trailing(n - 1)
  130. t = n >> s
  131. for base in bases:
  132. # Bases >= n are wrapped, bases < 2 are invalid
  133. if base >= n:
  134. base %= n
  135. if base >= 2:
  136. base = ZZ(base)
  137. if not _test(n, base, s, t):
  138. return False
  139. return True
  140. def _lucas_sequence(n, P, Q, k):
  141. """Return the modular Lucas sequence (U_k, V_k, Q_k).
  142. Given a Lucas sequence defined by P, Q, returns the kth values for
  143. U and V, along with Q^k, all modulo n. This is intended for use with
  144. possibly very large values of n and k, where the combinatorial functions
  145. would be completely unusable.
  146. The modular Lucas sequences are used in numerous places in number theory,
  147. especially in the Lucas compositeness tests and the various n + 1 proofs.
  148. Examples
  149. ========
  150. >>> from sympy.ntheory.primetest import _lucas_sequence
  151. >>> N = 10**2000 + 4561
  152. >>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
  153. (0, 2, 1)
  154. """
  155. D = P*P - 4*Q
  156. if n < 2:
  157. raise ValueError("n must be >= 2")
  158. if k < 0:
  159. raise ValueError("k must be >= 0")
  160. if D == 0:
  161. raise ValueError("D must not be zero")
  162. if k == 0:
  163. return _int_tuple(0, 2, Q)
  164. U = 1
  165. V = P
  166. Qk = Q
  167. b = _bitlength(k)
  168. if Q == 1:
  169. # Optimization for extra strong tests.
  170. while b > 1:
  171. U = (U*V) % n
  172. V = (V*V - 2) % n
  173. b -= 1
  174. if (k >> (b - 1)) & 1:
  175. U, V = U*P + V, V*P + U*D
  176. if U & 1:
  177. U += n
  178. if V & 1:
  179. V += n
  180. U, V = U >> 1, V >> 1
  181. elif P == 1 and Q == -1:
  182. # Small optimization for 50% of Selfridge parameters.
  183. while b > 1:
  184. U = (U*V) % n
  185. if Qk == 1:
  186. V = (V*V - 2) % n
  187. else:
  188. V = (V*V + 2) % n
  189. Qk = 1
  190. b -= 1
  191. if (k >> (b-1)) & 1:
  192. U, V = U + V, V + U*D
  193. if U & 1:
  194. U += n
  195. if V & 1:
  196. V += n
  197. U, V = U >> 1, V >> 1
  198. Qk = -1
  199. else:
  200. # The general case with any P and Q.
  201. while b > 1:
  202. U = (U*V) % n
  203. V = (V*V - 2*Qk) % n
  204. Qk *= Qk
  205. b -= 1
  206. if (k >> (b - 1)) & 1:
  207. U, V = U*P + V, V*P + U*D
  208. if U & 1:
  209. U += n
  210. if V & 1:
  211. V += n
  212. U, V = U >> 1, V >> 1
  213. Qk *= Q
  214. Qk %= n
  215. return _int_tuple(U % n, V % n, Qk)
  216. def _lucas_selfridge_params(n):
  217. """Calculates the Selfridge parameters (D, P, Q) for n. This is
  218. method A from page 1401 of Baillie and Wagstaff.
  219. References
  220. ==========
  221. .. [1] "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
  222. http://mpqs.free.fr/LucasPseudoprimes.pdf
  223. """
  224. from sympy.ntheory.residue_ntheory import jacobi_symbol
  225. D = 5
  226. while True:
  227. g = igcd(abs(D), n)
  228. if g > 1 and g != n:
  229. return (0, 0, 0)
  230. if jacobi_symbol(D, n) == -1:
  231. break
  232. if D > 0:
  233. D = -D - 2
  234. else:
  235. D = -D + 2
  236. return _int_tuple(D, 1, (1 - D)/4)
  237. def _lucas_extrastrong_params(n):
  238. """Calculates the "extra strong" parameters (D, P, Q) for n.
  239. References
  240. ==========
  241. .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
  242. https://oeis.org/A217719
  243. .. [1] https://en.wikipedia.org/wiki/Lucas_pseudoprime
  244. """
  245. from sympy.ntheory.residue_ntheory import jacobi_symbol
  246. P, Q, D = 3, 1, 5
  247. while True:
  248. g = igcd(D, n)
  249. if g > 1 and g != n:
  250. return (0, 0, 0)
  251. if jacobi_symbol(D, n) == -1:
  252. break
  253. P += 1
  254. D = P*P - 4
  255. return _int_tuple(D, P, Q)
  256. def is_lucas_prp(n):
  257. """Standard Lucas compositeness test with Selfridge parameters. Returns
  258. False if n is definitely composite, and True if n is a Lucas probable
  259. prime.
  260. This is typically used in combination with the Miller-Rabin test.
  261. References
  262. ==========
  263. - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
  264. http://mpqs.free.fr/LucasPseudoprimes.pdf
  265. - OEIS A217120: Lucas Pseudoprimes
  266. https://oeis.org/A217120
  267. - https://en.wikipedia.org/wiki/Lucas_pseudoprime
  268. Examples
  269. ========
  270. >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
  271. >>> for i in range(10000):
  272. ... if is_lucas_prp(i) and not isprime(i):
  273. ... print(i)
  274. 323
  275. 377
  276. 1159
  277. 1829
  278. 3827
  279. 5459
  280. 5777
  281. 9071
  282. 9179
  283. """
  284. n = as_int(n)
  285. if n == 2:
  286. return True
  287. if n < 2 or (n % 2) == 0:
  288. return False
  289. if is_square(n, False):
  290. return False
  291. D, P, Q = _lucas_selfridge_params(n)
  292. if D == 0:
  293. return False
  294. U, V, Qk = _lucas_sequence(n, P, Q, n+1)
  295. return U == 0
  296. def is_strong_lucas_prp(n):
  297. """Strong Lucas compositeness test with Selfridge parameters. Returns
  298. False if n is definitely composite, and True if n is a strong Lucas
  299. probable prime.
  300. This is often used in combination with the Miller-Rabin test, and
  301. in particular, when combined with M-R base 2 creates the strong BPSW test.
  302. References
  303. ==========
  304. - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
  305. http://mpqs.free.fr/LucasPseudoprimes.pdf
  306. - OEIS A217255: Strong Lucas Pseudoprimes
  307. https://oeis.org/A217255
  308. - https://en.wikipedia.org/wiki/Lucas_pseudoprime
  309. - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
  310. Examples
  311. ========
  312. >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
  313. >>> for i in range(20000):
  314. ... if is_strong_lucas_prp(i) and not isprime(i):
  315. ... print(i)
  316. 5459
  317. 5777
  318. 10877
  319. 16109
  320. 18971
  321. """
  322. from sympy.ntheory.factor_ import trailing
  323. n = as_int(n)
  324. if n == 2:
  325. return True
  326. if n < 2 or (n % 2) == 0:
  327. return False
  328. if is_square(n, False):
  329. return False
  330. D, P, Q = _lucas_selfridge_params(n)
  331. if D == 0:
  332. return False
  333. # remove powers of 2 from n+1 (= k * 2**s)
  334. s = trailing(n + 1)
  335. k = (n+1) >> s
  336. U, V, Qk = _lucas_sequence(n, P, Q, k)
  337. if U == 0 or V == 0:
  338. return True
  339. for r in range(1, s):
  340. V = (V*V - 2*Qk) % n
  341. if V == 0:
  342. return True
  343. Qk = pow(Qk, 2, n)
  344. return False
  345. def is_extra_strong_lucas_prp(n):
  346. """Extra Strong Lucas compositeness test. Returns False if n is
  347. definitely composite, and True if n is a "extra strong" Lucas probable
  348. prime.
  349. The parameters are selected using P = 3, Q = 1, then incrementing P until
  350. (D|n) == -1. The test itself is as defined in Grantham 2000, from the
  351. Mo and Jones preprint. The parameter selection and test are the same as
  352. used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
  353. page on Wikipedia.
  354. With these parameters, there are no counterexamples below 2^64 nor any
  355. known above that range. It is 20-50% faster than the strong test.
  356. Because of the different parameters selected, there is no relationship
  357. between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
  358. In particular, one is not a subset of the other.
  359. References
  360. ==========
  361. - "Frobenius Pseudoprimes", Jon Grantham, 2000.
  362. http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/
  363. - OEIS A217719: Extra Strong Lucas Pseudoprimes
  364. https://oeis.org/A217719
  365. - https://en.wikipedia.org/wiki/Lucas_pseudoprime
  366. Examples
  367. ========
  368. >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
  369. >>> for i in range(20000):
  370. ... if is_extra_strong_lucas_prp(i) and not isprime(i):
  371. ... print(i)
  372. 989
  373. 3239
  374. 5777
  375. 10877
  376. """
  377. # Implementation notes:
  378. # 1) the parameters differ from Thomas R. Nicely's. His parameter
  379. # selection leads to pseudoprimes that overlap M-R tests, and
  380. # contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
  381. # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
  382. # sequence must have Q=1. See Grantham theorem 2.3, any of the
  383. # references on the MathWorld page, or run it and see Q=-1 is wrong.
  384. from sympy.ntheory.factor_ import trailing
  385. n = as_int(n)
  386. if n == 2:
  387. return True
  388. if n < 2 or (n % 2) == 0:
  389. return False
  390. if is_square(n, False):
  391. return False
  392. D, P, Q = _lucas_extrastrong_params(n)
  393. if D == 0:
  394. return False
  395. # remove powers of 2 from n+1 (= k * 2**s)
  396. s = trailing(n + 1)
  397. k = (n+1) >> s
  398. U, V, Qk = _lucas_sequence(n, P, Q, k)
  399. if U == 0 and (V == 2 or V == n - 2):
  400. return True
  401. for r in range(1, s):
  402. if V == 0:
  403. return True
  404. V = (V*V - 2) % n
  405. return False
  406. def isprime(n):
  407. """
  408. Test if n is a prime number (True) or not (False). For n < 2^64 the
  409. answer is definitive; larger n values have a small probability of actually
  410. being pseudoprimes.
  411. Negative numbers (e.g. -2) are not considered prime.
  412. The first step is looking for trivial factors, which if found enables
  413. a quick return. Next, if the sieve is large enough, use bisection search
  414. on the sieve. For small numbers, a set of deterministic Miller-Rabin
  415. tests are performed with bases that are known to have no counterexamples
  416. in their range. Finally if the number is larger than 2^64, a strong
  417. BPSW test is performed. While this is a probable prime test and we
  418. believe counterexamples exist, there are no known counterexamples.
  419. Examples
  420. ========
  421. >>> from sympy.ntheory import isprime
  422. >>> isprime(13)
  423. True
  424. >>> isprime(13.0) # limited precision
  425. False
  426. >>> isprime(15)
  427. False
  428. Notes
  429. =====
  430. This routine is intended only for integer input, not numerical
  431. expressions which may represent numbers. Floats are also
  432. rejected as input because they represent numbers of limited
  433. precision. While it is tempting to permit 7.0 to represent an
  434. integer there are errors that may "pass silently" if this is
  435. allowed:
  436. >>> from sympy import Float, S
  437. >>> int(1e3) == 1e3 == 10**3
  438. True
  439. >>> int(1e23) == 1e23
  440. True
  441. >>> int(1e23) == 10**23
  442. False
  443. >>> near_int = 1 + S(1)/10**19
  444. >>> near_int == int(near_int)
  445. False
  446. >>> n = Float(near_int, 10) # truncated by precision
  447. >>> n == int(n)
  448. True
  449. >>> n = Float(near_int, 20)
  450. >>> n == int(n)
  451. False
  452. See Also
  453. ========
  454. sympy.ntheory.generate.primerange : Generates all primes in a given range
  455. sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n
  456. sympy.ntheory.generate.prime : Return the nth prime
  457. References
  458. ==========
  459. - https://en.wikipedia.org/wiki/Strong_pseudoprime
  460. - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980.
  461. http://mpqs.free.fr/LucasPseudoprimes.pdf
  462. - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
  463. """
  464. try:
  465. n = as_int(n)
  466. except ValueError:
  467. return False
  468. # Step 1, do quick composite testing via trial division. The individual
  469. # modulo tests benchmark faster than one or two primorial igcds for me.
  470. # The point here is just to speedily handle small numbers and many
  471. # composites. Step 2 only requires that n <= 2 get handled here.
  472. if n in [2, 3, 5]:
  473. return True
  474. if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
  475. return False
  476. if n < 49:
  477. return True
  478. if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
  479. (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
  480. (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
  481. return False
  482. if n < 2809:
  483. return True
  484. if n <= 23001:
  485. return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951]
  486. # bisection search on the sieve if the sieve is large enough
  487. from sympy.ntheory.generate import sieve as s
  488. if n <= s._list[-1]:
  489. l, u = s.search(n)
  490. return l == u
  491. # If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
  492. # This should be a bit faster than our step 2, and for large values will
  493. # be a lot faster than our step 3 (C+GMP vs. Python).
  494. if HAS_GMPY == 2:
  495. from gmpy2 import is_strong_prp, is_strong_selfridge_prp
  496. return is_strong_prp(n, 2) and is_strong_selfridge_prp(n)
  497. # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
  498. # https://miller-rabin.appspot.com/
  499. # for lists. We have made sure the M-R routine will successfully handle
  500. # bases larger than n, so we can use the minimal set.
  501. if n < 341531:
  502. return mr(n, [9345883071009581737])
  503. if n < 885594169:
  504. return mr(n, [725270293939359937, 3569819667048198375])
  505. if n < 350269456337:
  506. return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
  507. if n < 55245642489451:
  508. return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
  509. if n < 7999252175582851:
  510. return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
  511. if n < 585226005592931977:
  512. return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
  513. if n < 18446744073709551616:
  514. return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
  515. # We could do this instead at any point:
  516. #if n < 18446744073709551616:
  517. # return mr(n, [2]) and is_extra_strong_lucas_prp(n)
  518. # Here are tests that are safe for MR routines that don't understand
  519. # large bases.
  520. #if n < 9080191:
  521. # return mr(n, [31, 73])
  522. #if n < 19471033:
  523. # return mr(n, [2, 299417])
  524. #if n < 38010307:
  525. # return mr(n, [2, 9332593])
  526. #if n < 316349281:
  527. # return mr(n, [11000544, 31481107])
  528. #if n < 4759123141:
  529. # return mr(n, [2, 7, 61])
  530. #if n < 105936894253:
  531. # return mr(n, [2, 1005905886, 1340600841])
  532. #if n < 31858317218647:
  533. # return mr(n, [2, 642735, 553174392, 3046413974])
  534. #if n < 3071837692357849:
  535. # return mr(n, [2, 75088, 642735, 203659041, 3613982119])
  536. #if n < 18446744073709551616:
  537. # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
  538. # Step 3: BPSW.
  539. #
  540. # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
  541. # 44.0s old isprime using 46 bases
  542. # 5.3s strong BPSW + one random base
  543. # 4.3s extra strong BPSW + one random base
  544. # 4.1s strong BPSW
  545. # 3.2s extra strong BPSW
  546. # Classic BPSW from page 1401 of the paper. See alternate ideas below.
  547. return mr(n, [2]) and is_strong_lucas_prp(n)
  548. # Using extra strong test, which is somewhat faster
  549. #return mr(n, [2]) and is_extra_strong_lucas_prp(n)
  550. # Add a random M-R base
  551. #import random
  552. #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
  553. def is_gaussian_prime(num):
  554. r"""Test if num is a Gaussian prime number.
  555. References
  556. ==========
  557. .. [1] https://oeis.org/wiki/Gaussian_primes
  558. """
  559. num = sympify(num)
  560. a, b = num.as_real_imag()
  561. a = as_int(a, strict=False)
  562. b = as_int(b, strict=False)
  563. if a == 0:
  564. b = abs(b)
  565. return isprime(b) and b % 4 == 3
  566. elif b == 0:
  567. a = abs(a)
  568. return isprime(a) and a % 4 == 3
  569. return isprime(a**2 + b**2)