primetest.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. """
  2. Primality testing
  3. """
  4. from itertools import count
  5. from sympy.core.sympify import sympify
  6. from sympy.external.gmpy import (gmpy as _gmpy, gcd, jacobi,
  7. is_square as gmpy_is_square,
  8. bit_scan1, is_fermat_prp, is_euler_prp,
  9. is_selfridge_prp, is_strong_selfridge_prp,
  10. is_strong_bpsw_prp)
  11. from sympy.external.ntheory import _lucas_sequence
  12. from sympy.utilities.misc import as_int, filldedent
  13. # Note: This list should be updated whenever new Mersenne primes are found.
  14. # Refer: https://www.mersenne.org/
  15. MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
  16. 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
  17. 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
  18. 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933,
  19. 136279841)
  20. def is_fermat_pseudoprime(n, a):
  21. r"""Returns True if ``n`` is prime or is an odd composite integer that
  22. is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
  23. .. math ::
  24. a^{n-1} \equiv 1 \pmod{n}
  25. (where mod refers to the modulo operation).
  26. Parameters
  27. ==========
  28. n : Integer
  29. ``n`` is a positive integer.
  30. a : Integer
  31. ``a`` is a positive integer.
  32. ``a`` and ``n`` should be relatively prime.
  33. Returns
  34. =======
  35. bool : If ``n`` is prime, it always returns ``True``.
  36. The composite number that returns ``True`` is called an Fermat pseudoprime.
  37. Examples
  38. ========
  39. >>> from sympy.ntheory.primetest import is_fermat_pseudoprime
  40. >>> from sympy.ntheory.factor_ import isprime
  41. >>> for n in range(1, 1000):
  42. ... if is_fermat_pseudoprime(n, 2) and not isprime(n):
  43. ... print(n)
  44. 341
  45. 561
  46. 645
  47. References
  48. ==========
  49. .. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
  50. """
  51. n, a = as_int(n), as_int(a)
  52. if a == 1:
  53. return n == 2 or bool(n % 2)
  54. return is_fermat_prp(n, a)
  55. def is_euler_pseudoprime(n, a):
  56. r"""Returns True if ``n`` is prime or is an odd composite integer that
  57. is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
  58. .. math ::
  59. a^{(n-1)/2} \equiv \pm 1 \pmod{n}
  60. (where mod refers to the modulo operation).
  61. Parameters
  62. ==========
  63. n : Integer
  64. ``n`` is a positive integer.
  65. a : Integer
  66. ``a`` is a positive integer.
  67. ``a`` and ``n`` should be relatively prime.
  68. Returns
  69. =======
  70. bool : If ``n`` is prime, it always returns ``True``.
  71. The composite number that returns ``True`` is called an Euler pseudoprime.
  72. Examples
  73. ========
  74. >>> from sympy.ntheory.primetest import is_euler_pseudoprime
  75. >>> from sympy.ntheory.factor_ import isprime
  76. >>> for n in range(1, 1000):
  77. ... if is_euler_pseudoprime(n, 2) and not isprime(n):
  78. ... print(n)
  79. 341
  80. 561
  81. References
  82. ==========
  83. .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
  84. """
  85. n, a = as_int(n), as_int(a)
  86. if a < 1:
  87. raise ValueError("a should be an integer greater than 0")
  88. if n < 1:
  89. raise ValueError("n should be an integer greater than 0")
  90. if n == 1:
  91. return False
  92. if a == 1:
  93. return n == 2 or bool(n % 2) # (prime or odd composite)
  94. if n % 2 == 0:
  95. return n == 2
  96. if gcd(n, a) != 1:
  97. raise ValueError("The two numbers should be relatively prime")
  98. return pow(a, (n - 1) // 2, n) in [1, n - 1]
  99. def is_euler_jacobi_pseudoprime(n, a):
  100. r"""Returns True if ``n`` is prime or is an odd composite integer that
  101. is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
  102. .. math ::
  103. a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}
  104. (where mod refers to the modulo operation).
  105. Parameters
  106. ==========
  107. n : Integer
  108. ``n`` is a positive integer.
  109. a : Integer
  110. ``a`` is a positive integer.
  111. ``a`` and ``n`` should be relatively prime.
  112. Returns
  113. =======
  114. bool : If ``n`` is prime, it always returns ``True``.
  115. The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.
  116. Examples
  117. ========
  118. >>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
  119. >>> from sympy.ntheory.factor_ import isprime
  120. >>> for n in range(1, 1000):
  121. ... if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
  122. ... print(n)
  123. 561
  124. References
  125. ==========
  126. .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
  127. """
  128. n, a = as_int(n), as_int(a)
  129. if a == 1:
  130. return n == 2 or bool(n % 2)
  131. return is_euler_prp(n, a)
  132. def is_square(n, prep=True):
  133. """Return True if n == a * a for some integer a, else False.
  134. If n is suspected of *not* being a square then this is a
  135. quick method of confirming that it is not.
  136. Examples
  137. ========
  138. >>> from sympy.ntheory.primetest import is_square
  139. >>> is_square(25)
  140. True
  141. >>> is_square(2)
  142. False
  143. References
  144. ==========
  145. .. [1] https://mersenneforum.org/showpost.php?p=110896
  146. See Also
  147. ========
  148. sympy.core.intfunc.isqrt
  149. """
  150. if prep:
  151. n = as_int(n)
  152. if n < 0:
  153. return False
  154. if n in (0, 1):
  155. return True
  156. return gmpy_is_square(n)
  157. def _test(n, base, s, t):
  158. """Miller-Rabin strong pseudoprime test for one base.
  159. Return False if n is definitely composite, True if n is
  160. probably prime, with a probability greater than 3/4.
  161. """
  162. # do the Fermat test
  163. b = pow(base, t, n)
  164. if b == 1 or b == n - 1:
  165. return True
  166. for _ in range(s - 1):
  167. b = pow(b, 2, n)
  168. if b == n - 1:
  169. return True
  170. # see I. Niven et al. "An Introduction to Theory of Numbers", page 78
  171. if b == 1:
  172. return False
  173. return False
  174. def mr(n, bases):
  175. """Perform a Miller-Rabin strong pseudoprime test on n using a
  176. given list of bases/witnesses.
  177. References
  178. ==========
  179. .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
  180. A Computational Perspective", Springer, 2nd edition, 135-138
  181. A list of thresholds and the bases they require are here:
  182. https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
  183. Examples
  184. ========
  185. >>> from sympy.ntheory.primetest import mr
  186. >>> mr(1373651, [2, 3])
  187. False
  188. >>> mr(479001599, [31, 73])
  189. True
  190. """
  191. from sympy.polys.domains import ZZ
  192. n = as_int(n)
  193. if n < 2 or (n > 2 and n % 2 == 0):
  194. return False
  195. # remove powers of 2 from n-1 (= t * 2**s)
  196. s = bit_scan1(n - 1)
  197. t = n >> s
  198. for base in bases:
  199. # Bases >= n are wrapped, bases < 2 are invalid
  200. if base >= n:
  201. base %= n
  202. if base >= 2:
  203. base = ZZ(base)
  204. if not _test(n, base, s, t):
  205. return False
  206. return True
  207. def _lucas_extrastrong_params(n):
  208. """Calculates the "extra strong" parameters (D, P, Q) for n.
  209. Parameters
  210. ==========
  211. n : int
  212. positive odd integer
  213. Returns
  214. =======
  215. D, P, Q: "extra strong" parameters.
  216. ``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.
  217. Examples
  218. ========
  219. >>> from sympy.ntheory.primetest import _lucas_extrastrong_params
  220. >>> _lucas_extrastrong_params(101)
  221. (12, 4, 1)
  222. >>> _lucas_extrastrong_params(15)
  223. (0, 0, 0)
  224. References
  225. ==========
  226. .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
  227. https://oeis.org/A217719
  228. .. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime
  229. """
  230. for P in count(3):
  231. D = P**2 - 4
  232. j = jacobi(D, n)
  233. if j == -1:
  234. return (D, P, 1)
  235. elif j == 0 and D % n:
  236. return (0, 0, 0)
  237. def is_lucas_prp(n):
  238. """Standard Lucas compositeness test with Selfridge parameters. Returns
  239. False if n is definitely composite, and True if n is a Lucas probable
  240. prime.
  241. This is typically used in combination with the Miller-Rabin test.
  242. References
  243. ==========
  244. .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
  245. Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
  246. https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
  247. http://mpqs.free.fr/LucasPseudoprimes.pdf
  248. .. [2] OEIS A217120: Lucas Pseudoprimes
  249. https://oeis.org/A217120
  250. .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
  251. Examples
  252. ========
  253. >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
  254. >>> for i in range(10000):
  255. ... if is_lucas_prp(i) and not isprime(i):
  256. ... print(i)
  257. 323
  258. 377
  259. 1159
  260. 1829
  261. 3827
  262. 5459
  263. 5777
  264. 9071
  265. 9179
  266. """
  267. n = as_int(n)
  268. if n < 2:
  269. return False
  270. return is_selfridge_prp(n)
  271. def is_strong_lucas_prp(n):
  272. """Strong Lucas compositeness test with Selfridge parameters. Returns
  273. False if n is definitely composite, and True if n is a strong Lucas
  274. probable prime.
  275. This is often used in combination with the Miller-Rabin test, and
  276. in particular, when combined with M-R base 2 creates the strong BPSW test.
  277. References
  278. ==========
  279. .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
  280. Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
  281. https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
  282. http://mpqs.free.fr/LucasPseudoprimes.pdf
  283. .. [2] OEIS A217255: Strong Lucas Pseudoprimes
  284. https://oeis.org/A217255
  285. .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
  286. .. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
  287. Examples
  288. ========
  289. >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
  290. >>> for i in range(20000):
  291. ... if is_strong_lucas_prp(i) and not isprime(i):
  292. ... print(i)
  293. 5459
  294. 5777
  295. 10877
  296. 16109
  297. 18971
  298. """
  299. n = as_int(n)
  300. if n < 2:
  301. return False
  302. return is_strong_selfridge_prp(n)
  303. def is_extra_strong_lucas_prp(n):
  304. """Extra Strong Lucas compositeness test. Returns False if n is
  305. definitely composite, and True if n is an "extra strong" Lucas probable
  306. prime.
  307. The parameters are selected using P = 3, Q = 1, then incrementing P until
  308. (D|n) == -1. The test itself is as defined in [1]_, from the
  309. Mo and Jones preprint. The parameter selection and test are the same as
  310. used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
  311. page on Wikipedia.
  312. It is 20-50% faster than the strong test.
  313. Because of the different parameters selected, there is no relationship
  314. between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
  315. In particular, one is not a subset of the other.
  316. References
  317. ==========
  318. .. [1] Jon Grantham, Frobenius Pseudoprimes,
  319. Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
  320. https://doi.org/10.1090%2FS0025-5718-00-01197-2
  321. .. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
  322. https://oeis.org/A217719
  323. .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
  324. Examples
  325. ========
  326. >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
  327. >>> for i in range(20000):
  328. ... if is_extra_strong_lucas_prp(i) and not isprime(i):
  329. ... print(i)
  330. 989
  331. 3239
  332. 5777
  333. 10877
  334. """
  335. # Implementation notes:
  336. # 1) the parameters differ from Thomas R. Nicely's. His parameter
  337. # selection leads to pseudoprimes that overlap M-R tests, and
  338. # contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
  339. # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas
  340. # sequence must have Q=1. See Grantham theorem 2.3, any of the
  341. # references on the MathWorld page, or run it and see Q=-1 is wrong.
  342. n = as_int(n)
  343. if n == 2:
  344. return True
  345. if n < 2 or (n % 2) == 0:
  346. return False
  347. if gmpy_is_square(n):
  348. return False
  349. D, P, Q = _lucas_extrastrong_params(n)
  350. if D == 0:
  351. return False
  352. # remove powers of 2 from n+1 (= k * 2**s)
  353. s = bit_scan1(n + 1)
  354. k = (n + 1) >> s
  355. U, V, _ = _lucas_sequence(n, P, Q, k)
  356. if U == 0 and (V == 2 or V == n - 2):
  357. return True
  358. for _ in range(1, s):
  359. if V == 0:
  360. return True
  361. V = (V*V - 2) % n
  362. return False
  363. def proth_test(n):
  364. r""" Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.
  365. Parameters
  366. ==========
  367. n : Integer
  368. ``n`` is Proth number
  369. Returns
  370. =======
  371. bool : If ``True``, then ``n`` is the Proth prime
  372. Raises
  373. ======
  374. ValueError
  375. If ``n`` is not Proth number.
  376. Examples
  377. ========
  378. >>> from sympy.ntheory.primetest import proth_test
  379. >>> proth_test(41)
  380. True
  381. >>> proth_test(57)
  382. False
  383. References
  384. ==========
  385. .. [1] https://en.wikipedia.org/wiki/Proth_prime
  386. """
  387. n = as_int(n)
  388. if n < 3:
  389. raise ValueError("n is not Proth number")
  390. m = bit_scan1(n - 1)
  391. k = n >> m
  392. if m < k.bit_length():
  393. raise ValueError("n is not Proth number")
  394. if n % 3 == 0:
  395. return n == 3
  396. if k % 3: # n % 12 == 5
  397. return pow(3, n >> 1, n) == n - 1
  398. # If `n` is a square number, then `jacobi(a, n) = 1` for any `a`
  399. if gmpy_is_square(n):
  400. return False
  401. # `a` may be chosen at random.
  402. # In any case, we want to find `a` such that `jacobi(a, n) = -1`.
  403. for a in range(5, n):
  404. j = jacobi(a, n)
  405. if j == -1:
  406. return pow(a, n >> 1, n) == n - 1
  407. if j == 0:
  408. return False
  409. def _lucas_lehmer_primality_test(p):
  410. r""" Test if the Mersenne number `M_p = 2^p-1` is prime.
  411. Parameters
  412. ==========
  413. p : int
  414. ``p`` is an odd prime number
  415. Returns
  416. =======
  417. bool : If ``True``, then `M_p` is the Mersenne prime
  418. Examples
  419. ========
  420. >>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
  421. >>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
  422. True
  423. >>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
  424. False
  425. See Also
  426. ========
  427. is_mersenne_prime
  428. References
  429. ==========
  430. .. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
  431. """
  432. v = 4
  433. m = 2**p - 1
  434. for _ in range(p - 2):
  435. v = pow(v, 2, m) - 2
  436. return v == 0
  437. def is_mersenne_prime(n):
  438. """Returns True if ``n`` is a Mersenne prime, else False.
  439. A Mersenne prime is a prime number having the form `2^i - 1`.
  440. Examples
  441. ========
  442. >>> from sympy.ntheory.factor_ import is_mersenne_prime
  443. >>> is_mersenne_prime(6)
  444. False
  445. >>> is_mersenne_prime(127)
  446. True
  447. References
  448. ==========
  449. .. [1] https://mathworld.wolfram.com/MersennePrime.html
  450. """
  451. n = as_int(n)
  452. if n < 1:
  453. return False
  454. if n & (n + 1):
  455. # n is not Mersenne number
  456. return False
  457. p = n.bit_length()
  458. if p in MERSENNE_PRIME_EXPONENTS:
  459. return True
  460. if p < 65_000_000 or not isprime(p):
  461. # According to GIMPS, verification was completed on September 19, 2023 for p less than 65 million.
  462. # https://www.mersenne.org/report_milestones/
  463. # If p is composite number, then n=2**p-1 is composite number.
  464. return False
  465. result = _lucas_lehmer_primality_test(p)
  466. if result:
  467. raise ValueError(filldedent('''
  468. This Mersenne Prime, 2^%s - 1, should
  469. be added to SymPy's known values.''' % p))
  470. return result
  471. _MR_BASES_32 = [15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295,
  472. 2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471,
  473. 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763,
  474. 4852, 5012, 3185, 1333, 6227,5298, 1074, 2391, 5113, 7061,
  475. 803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556,
  476. 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373,
  477. 6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467,
  478. 3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888,
  479. 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875,
  480. 3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165,
  481. 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377,
  482. 1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601,
  483. 6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360,
  484. 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031,
  485. 2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725,
  486. 3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371,
  487. 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727,
  488. 3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126,
  489. 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674,
  490. 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007,
  491. 35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521,
  492. 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166,
  493. 1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197,
  494. 13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449,
  495. 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194]
  496. def isprime(n):
  497. """
  498. Test if n is a prime number (True) or not (False). For n < 2^64 the
  499. answer is definitive; larger n values have a small probability of actually
  500. being pseudoprimes.
  501. Negative numbers (e.g. -2) are not considered prime.
  502. The first step is looking for trivial factors, which if found enables
  503. a quick return. Next, if the sieve is large enough, use bisection search
  504. on the sieve. For small numbers, a set of deterministic Miller-Rabin
  505. tests are performed with bases that are known to have no counterexamples
  506. in their range. Finally if the number is larger than 2^64, a strong
  507. BPSW test is performed. While this is a probable prime test and we
  508. believe counterexamples exist, there are no known counterexamples.
  509. Examples
  510. ========
  511. >>> from sympy.ntheory import isprime
  512. >>> isprime(13)
  513. True
  514. >>> isprime(15)
  515. False
  516. Notes
  517. =====
  518. This routine is intended only for integer input, not numerical
  519. expressions which may represent numbers. Floats are also
  520. rejected as input because they represent numbers of limited
  521. precision. While it is tempting to permit 7.0 to represent an
  522. integer there are errors that may "pass silently" if this is
  523. allowed:
  524. >>> from sympy import Float, S
  525. >>> int(1e3) == 1e3 == 10**3
  526. True
  527. >>> int(1e23) == 1e23
  528. True
  529. >>> int(1e23) == 10**23
  530. False
  531. >>> near_int = 1 + S(1)/10**19
  532. >>> near_int == int(near_int)
  533. False
  534. >>> n = Float(near_int, 10) # truncated by precision
  535. >>> n % 1 == 0
  536. True
  537. >>> n = Float(near_int, 20)
  538. >>> n % 1 == 0
  539. False
  540. See Also
  541. ========
  542. sympy.ntheory.generate.primerange : Generates all primes in a given range
  543. sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
  544. sympy.ntheory.generate.prime : Return the nth prime
  545. References
  546. ==========
  547. .. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
  548. .. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
  549. Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
  550. https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
  551. http://mpqs.free.fr/LucasPseudoprimes.pdf
  552. .. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
  553. """
  554. n = as_int(n)
  555. # Step 1, do quick composite testing via trial division. The individual
  556. # modulo tests benchmark faster than one or two primorial igcds for me.
  557. # The point here is just to speedily handle small numbers and many
  558. # composites. Step 2 only requires that n <= 2 get handled here.
  559. if n in [2, 3, 5]:
  560. return True
  561. if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
  562. return False
  563. if n < 49:
  564. return True
  565. if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
  566. (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
  567. (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
  568. return False
  569. if n < 2809:
  570. return True
  571. if n < 65077:
  572. # There are only five Euler pseudoprimes with a least prime factor greater than 47
  573. return pow(2, n >> 1, n) in [1, n - 1] and n not in [8321, 31621, 42799, 49141, 49981]
  574. # bisection search on the sieve if the sieve is large enough
  575. from sympy.ntheory.generate import sieve as s
  576. if n <= s._list[-1]:
  577. l, u = s.search(n)
  578. return l == u
  579. from sympy.ntheory.factor_ import factor_cache
  580. if (ret := factor_cache.get(n)) is not None:
  581. return ret == n
  582. # If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
  583. # This should be a bit faster than our step 2, and for large values will
  584. # be a lot faster than our step 3 (C+GMP vs. Python).
  585. if _gmpy is not None:
  586. return is_strong_bpsw_prp(n)
  587. # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See:
  588. # https://miller-rabin.appspot.com/
  589. # for lists. We have made sure the M-R routine will successfully handle
  590. # bases larger than n, so we can use the minimal set.
  591. # In September 2015 deterministic numbers were extended to over 2^81.
  592. # https://arxiv.org/pdf/1509.00864.pdf
  593. # https://oeis.org/A014233
  594. if n < 341531:
  595. return mr(n, [9345883071009581737])
  596. if n < 4296595241:
  597. # Michal Forisek and Jakub Jancina,
  598. # Fast Primality Testing for Integers That Fit into a Machine Word
  599. # https://ceur-ws.org/Vol-1326/020-Forisek.pdf
  600. h = ((n >> 16) ^ n) * 0x45d9f3b
  601. h = ((h >> 16) ^ h) * 0x45d9f3b
  602. h = ((h >> 16) ^ h) & 255
  603. return mr(n, [_MR_BASES_32[h]])
  604. if n < 350269456337:
  605. return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
  606. if n < 55245642489451:
  607. return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
  608. if n < 7999252175582851:
  609. return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
  610. if n < 585226005592931977:
  611. return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
  612. if n < 18446744073709551616:
  613. return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
  614. if n < 318665857834031151167461:
  615. return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
  616. if n < 3317044064679887385961981:
  617. return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
  618. # We could do this instead at any point:
  619. #if n < 18446744073709551616:
  620. # return mr(n, [2]) and is_extra_strong_lucas_prp(n)
  621. # Here are tests that are safe for MR routines that don't understand
  622. # large bases.
  623. #if n < 9080191:
  624. # return mr(n, [31, 73])
  625. #if n < 19471033:
  626. # return mr(n, [2, 299417])
  627. #if n < 38010307:
  628. # return mr(n, [2, 9332593])
  629. #if n < 316349281:
  630. # return mr(n, [11000544, 31481107])
  631. #if n < 4759123141:
  632. # return mr(n, [2, 7, 61])
  633. #if n < 105936894253:
  634. # return mr(n, [2, 1005905886, 1340600841])
  635. #if n < 31858317218647:
  636. # return mr(n, [2, 642735, 553174392, 3046413974])
  637. #if n < 3071837692357849:
  638. # return mr(n, [2, 75088, 642735, 203659041, 3613982119])
  639. #if n < 18446744073709551616:
  640. # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
  641. # Step 3: BPSW.
  642. #
  643. # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
  644. # 44.0s old isprime using 46 bases
  645. # 5.3s strong BPSW + one random base
  646. # 4.3s extra strong BPSW + one random base
  647. # 4.1s strong BPSW
  648. # 3.2s extra strong BPSW
  649. # Classic BPSW from page 1401 of the paper. See alternate ideas below.
  650. return is_strong_bpsw_prp(n)
  651. # Using extra strong test, which is somewhat faster
  652. #return mr(n, [2]) and is_extra_strong_lucas_prp(n)
  653. # Add a random M-R base
  654. #import random
  655. #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
  656. def is_gaussian_prime(num):
  657. r"""Test if num is a Gaussian prime number.
  658. References
  659. ==========
  660. .. [1] https://oeis.org/wiki/Gaussian_primes
  661. """
  662. num = sympify(num)
  663. a, b = num.as_real_imag()
  664. a = as_int(a, strict=False)
  665. b = as_int(b, strict=False)
  666. if a == 0:
  667. b = abs(b)
  668. return isprime(b) and b % 4 == 3
  669. elif b == 0:
  670. a = abs(a)
  671. return isprime(a) and a % 4 == 3
  672. return isprime(a**2 + b**2)