prime.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package big
  5. import "math/rand"
  6. // ProbablyPrime reports whether x is probably prime,
  7. // applying the Miller-Rabin test with n pseudorandomly chosen bases
  8. // as well as a Baillie-PSW test.
  9. //
  10. // If x is prime, ProbablyPrime returns true.
  11. // If x is chosen randomly and not prime, ProbablyPrime probably returns false.
  12. // The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.
  13. //
  14. // ProbablyPrime is 100% accurate for inputs less than 2⁶⁴.
  15. // See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149,
  16. // and FIPS 186-4 Appendix F for further discussion of the error probabilities.
  17. //
  18. // ProbablyPrime is not suitable for judging primes that an adversary may
  19. // have crafted to fool the test.
  20. //
  21. // As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test.
  22. // Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked.
  23. func (x *Int) ProbablyPrime(n int) bool {
  24. // Note regarding the doc comment above:
  25. // It would be more precise to say that the Baillie-PSW test uses the
  26. // extra strong Lucas test as its Lucas test, but since no one knows
  27. // how to tell any of the Lucas tests apart inside a Baillie-PSW test
  28. // (they all work equally well empirically), that detail need not be
  29. // documented or implicitly guaranteed.
  30. // The comment does avoid saying "the" Baillie-PSW test
  31. // because of this general ambiguity.
  32. if n < 0 {
  33. panic("negative n for ProbablyPrime")
  34. }
  35. if x.neg || len(x.abs) == 0 {
  36. return false
  37. }
  38. // primeBitMask records the primes < 64.
  39. const primeBitMask uint64 = 1<<2 | 1<<3 | 1<<5 | 1<<7 |
  40. 1<<11 | 1<<13 | 1<<17 | 1<<19 | 1<<23 | 1<<29 | 1<<31 |
  41. 1<<37 | 1<<41 | 1<<43 | 1<<47 | 1<<53 | 1<<59 | 1<<61
  42. w := x.abs[0]
  43. if len(x.abs) == 1 && w < 64 {
  44. return primeBitMask&(1<<w) != 0
  45. }
  46. if w&1 == 0 {
  47. return false // x is even
  48. }
  49. const primesA = 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 37
  50. const primesB = 29 * 31 * 41 * 43 * 47 * 53
  51. var rA, rB uint32
  52. switch _W {
  53. case 32:
  54. rA = uint32(x.abs.modW(primesA))
  55. rB = uint32(x.abs.modW(primesB))
  56. case 64:
  57. r := x.abs.modW((primesA * primesB) & _M)
  58. rA = uint32(r % primesA)
  59. rB = uint32(r % primesB)
  60. default:
  61. panic("math/big: invalid word size")
  62. }
  63. if rA%3 == 0 || rA%5 == 0 || rA%7 == 0 || rA%11 == 0 || rA%13 == 0 || rA%17 == 0 || rA%19 == 0 || rA%23 == 0 || rA%37 == 0 ||
  64. rB%29 == 0 || rB%31 == 0 || rB%41 == 0 || rB%43 == 0 || rB%47 == 0 || rB%53 == 0 {
  65. return false
  66. }
  67. return x.abs.probablyPrimeMillerRabin(n+1, true) && x.abs.probablyPrimeLucas()
  68. }
  69. // probablyPrimeMillerRabin reports whether n passes reps rounds of the
  70. // Miller-Rabin primality test, using pseudo-randomly chosen bases.
  71. // If force2 is true, one of the rounds is forced to use base 2.
  72. // See Handbook of Applied Cryptography, p. 139, Algorithm 4.24.
  73. // The number n is known to be non-zero.
  74. func (n nat) probablyPrimeMillerRabin(reps int, force2 bool) bool {
  75. nm1 := nat(nil).sub(n, natOne)
  76. // determine q, k such that nm1 = q << k
  77. k := nm1.trailingZeroBits()
  78. q := nat(nil).shr(nm1, k)
  79. nm3 := nat(nil).sub(nm1, natTwo)
  80. rand := rand.New(rand.NewSource(int64(n[0])))
  81. var x, y, quotient nat
  82. nm3Len := nm3.bitLen()
  83. NextRandom:
  84. for i := 0; i < reps; i++ {
  85. if i == reps-1 && force2 {
  86. x = x.set(natTwo)
  87. } else {
  88. x = x.random(rand, nm3, nm3Len)
  89. x = x.add(x, natTwo)
  90. }
  91. y = y.expNN(x, q, n)
  92. if y.cmp(natOne) == 0 || y.cmp(nm1) == 0 {
  93. continue
  94. }
  95. for j := uint(1); j < k; j++ {
  96. y = y.sqr(y)
  97. quotient, y = quotient.div(y, y, n)
  98. if y.cmp(nm1) == 0 {
  99. continue NextRandom
  100. }
  101. if y.cmp(natOne) == 0 {
  102. return false
  103. }
  104. }
  105. return false
  106. }
  107. return true
  108. }
  109. // probablyPrimeLucas reports whether n passes the "almost extra strong" Lucas probable prime test,
  110. // using Baillie-OEIS parameter selection. This corresponds to "AESLPSP" on Jacobsen's tables (link below).
  111. // The combination of this test and a Miller-Rabin/Fermat test with base 2 gives a Baillie-PSW test.
  112. //
  113. // References:
  114. //
  115. // Baillie and Wagstaff, "Lucas Pseudoprimes", Mathematics of Computation 35(152),
  116. // October 1980, pp. 1391-1417, especially page 1401.
  117. // https://www.ams.org/journals/mcom/1980-35-152/S0025-5718-1980-0583518-6/S0025-5718-1980-0583518-6.pdf
  118. //
  119. // Grantham, "Frobenius Pseudoprimes", Mathematics of Computation 70(234),
  120. // March 2000, pp. 873-891.
  121. // https://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/S0025-5718-00-01197-2.pdf
  122. //
  123. // Baillie, "Extra strong Lucas pseudoprimes", OEIS A217719, https://oeis.org/A217719.
  124. //
  125. // Jacobsen, "Pseudoprime Statistics, Tables, and Data", http://ntheory.org/pseudoprimes.html.
  126. //
  127. // Nicely, "The Baillie-PSW Primality Test", http://www.trnicely.net/misc/bpsw.html.
  128. // (Note that Nicely's definition of the "extra strong" test gives the wrong Jacobi condition,
  129. // as pointed out by Jacobsen.)
  130. //
  131. // Crandall and Pomerance, Prime Numbers: A Computational Perspective, 2nd ed.
  132. // Springer, 2005.
  133. func (n nat) probablyPrimeLucas() bool {
  134. // Discard 0, 1.
  135. if len(n) == 0 || n.cmp(natOne) == 0 {
  136. return false
  137. }
  138. // Two is the only even prime.
  139. // Already checked by caller, but here to allow testing in isolation.
  140. if n[0]&1 == 0 {
  141. return n.cmp(natTwo) == 0
  142. }
  143. // Baillie-OEIS "method C" for choosing D, P, Q,
  144. // as in https://oeis.org/A217719/a217719.txt:
  145. // try increasing P ≥ 3 such that D = P² - 4 (so Q = 1)
  146. // until Jacobi(D, n) = -1.
  147. // The search is expected to succeed for non-square n after just a few trials.
  148. // After more than expected failures, check whether n is square
  149. // (which would cause Jacobi(D, n) = 1 for all D not dividing n).
  150. p := Word(3)
  151. d := nat{1}
  152. t1 := nat(nil) // temp
  153. intD := &Int{abs: d}
  154. intN := &Int{abs: n}
  155. for ; ; p++ {
  156. if p > 10000 {
  157. // This is widely believed to be impossible.
  158. // If we get a report, we'll want the exact number n.
  159. panic("math/big: internal error: cannot find (D/n) = -1 for " + intN.String())
  160. }
  161. d[0] = p*p - 4
  162. j := Jacobi(intD, intN)
  163. if j == -1 {
  164. break
  165. }
  166. if j == 0 {
  167. // d = p²-4 = (p-2)(p+2).
  168. // If (d/n) == 0 then d shares a prime factor with n.
  169. // Since the loop proceeds in increasing p and starts with p-2==1,
  170. // the shared prime factor must be p+2.
  171. // If p+2 == n, then n is prime; otherwise p+2 is a proper factor of n.
  172. return len(n) == 1 && n[0] == p+2
  173. }
  174. if p == 40 {
  175. // We'll never find (d/n) = -1 if n is a square.
  176. // If n is a non-square we expect to find a d in just a few attempts on average.
  177. // After 40 attempts, take a moment to check if n is indeed a square.
  178. t1 = t1.sqrt(n)
  179. t1 = t1.sqr(t1)
  180. if t1.cmp(n) == 0 {
  181. return false
  182. }
  183. }
  184. }
  185. // Grantham definition of "extra strong Lucas pseudoprime", after Thm 2.3 on p. 876
  186. // (D, P, Q above have become Δ, b, 1):
  187. //
  188. // Let U_n = U_n(b, 1), V_n = V_n(b, 1), and Δ = b²-4.
  189. // An extra strong Lucas pseudoprime to base b is a composite n = 2^r s + Jacobi(Δ, n),
  190. // where s is odd and gcd(n, 2*Δ) = 1, such that either (i) U_s ≡ 0 mod n and V_s ≡ ±2 mod n,
  191. // or (ii) V_{2^t s} ≡ 0 mod n for some 0 ≤ t < r-1.
  192. //
  193. // We know gcd(n, Δ) = 1 or else we'd have found Jacobi(d, n) == 0 above.
  194. // We know gcd(n, 2) = 1 because n is odd.
  195. //
  196. // Arrange s = (n - Jacobi(Δ, n)) / 2^r = (n+1) / 2^r.
  197. s := nat(nil).add(n, natOne)
  198. r := int(s.trailingZeroBits())
  199. s = s.shr(s, uint(r))
  200. nm2 := nat(nil).sub(n, natTwo) // n-2
  201. // We apply the "almost extra strong" test, which checks the above conditions
  202. // except for U_s ≡ 0 mod n, which allows us to avoid computing any U_k values.
  203. // Jacobsen points out that maybe we should just do the full extra strong test:
  204. // "It is also possible to recover U_n using Crandall and Pomerance equation 3.13:
  205. // U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test
  206. // at the cost of a single modular inversion. This computation is easy and fast in GMP,
  207. // so we can get the full extra-strong test at essentially the same performance as the
  208. // almost extra strong test."
  209. // Compute Lucas sequence V_s(b, 1), where:
  210. //
  211. // V(0) = 2
  212. // V(1) = P
  213. // V(k) = P V(k-1) - Q V(k-2).
  214. //
  215. // (Remember that due to method C above, P = b, Q = 1.)
  216. //
  217. // In general V(k) = α^k + β^k, where α and β are roots of x² - Px + Q.
  218. // Crandall and Pomerance (p.147) observe that for 0 ≤ j ≤ k,
  219. //
  220. // V(j+k) = V(j)V(k) - V(k-j).
  221. //
  222. // So in particular, to quickly double the subscript:
  223. //
  224. // V(2k) = V(k)² - 2
  225. // V(2k+1) = V(k) V(k+1) - P
  226. //
  227. // We can therefore start with k=0 and build up to k=s in log₂(s) steps.
  228. natP := nat(nil).setWord(p)
  229. vk := nat(nil).setWord(2)
  230. vk1 := nat(nil).setWord(p)
  231. t2 := nat(nil) // temp
  232. for i := int(s.bitLen()); i >= 0; i-- {
  233. if s.bit(uint(i)) != 0 {
  234. // k' = 2k+1
  235. // V(k') = V(2k+1) = V(k) V(k+1) - P.
  236. t1 = t1.mul(vk, vk1)
  237. t1 = t1.add(t1, n)
  238. t1 = t1.sub(t1, natP)
  239. t2, vk = t2.div(vk, t1, n)
  240. // V(k'+1) = V(2k+2) = V(k+1)² - 2.
  241. t1 = t1.sqr(vk1)
  242. t1 = t1.add(t1, nm2)
  243. t2, vk1 = t2.div(vk1, t1, n)
  244. } else {
  245. // k' = 2k
  246. // V(k'+1) = V(2k+1) = V(k) V(k+1) - P.
  247. t1 = t1.mul(vk, vk1)
  248. t1 = t1.add(t1, n)
  249. t1 = t1.sub(t1, natP)
  250. t2, vk1 = t2.div(vk1, t1, n)
  251. // V(k') = V(2k) = V(k)² - 2
  252. t1 = t1.sqr(vk)
  253. t1 = t1.add(t1, nm2)
  254. t2, vk = t2.div(vk, t1, n)
  255. }
  256. }
  257. // Now k=s, so vk = V(s). Check V(s) ≡ ±2 (mod n).
  258. if vk.cmp(natTwo) == 0 || vk.cmp(nm2) == 0 {
  259. // Check U(s) ≡ 0.
  260. // As suggested by Jacobsen, apply Crandall and Pomerance equation 3.13:
  261. //
  262. // U(k) = D⁻¹ (2 V(k+1) - P V(k))
  263. //
  264. // Since we are checking for U(k) == 0 it suffices to check 2 V(k+1) == P V(k) mod n,
  265. // or P V(k) - 2 V(k+1) == 0 mod n.
  266. t1 := t1.mul(vk, natP)
  267. t2 := t2.shl(vk1, 1)
  268. if t1.cmp(t2) < 0 {
  269. t1, t2 = t2, t1
  270. }
  271. t1 = t1.sub(t1, t2)
  272. t3 := vk1 // steal vk1, no longer needed below
  273. vk1 = nil
  274. _ = vk1
  275. t2, t3 = t2.div(t3, t1, n)
  276. if len(t3) == 0 {
  277. return true
  278. }
  279. }
  280. // Check V(2^t s) ≡ 0 mod n for some 0 ≤ t < r-1.
  281. for t := 0; t < r-1; t++ {
  282. if len(vk) == 0 { // vk == 0
  283. return true
  284. }
  285. // Optimization: V(k) = 2 is a fixed point for V(k') = V(k)² - 2,
  286. // so if V(k) = 2, we can stop: we will never find a future V(k) == 0.
  287. if len(vk) == 1 && vk[0] == 2 { // vk == 2
  288. return false
  289. }
  290. // k' = 2k
  291. // V(k') = V(2k) = V(k)² - 2
  292. t1 = t1.sqr(vk)
  293. t1 = t1.sub(t1, natTwo)
  294. t2, vk = t2.div(vk, t1, n)
  295. }
  296. return false
  297. }