Primality Testing
Fermat, Miller–Rabin and the AKS theorem.
Is prime? Trial division would try about divisors. A Miller–Rabin test with a dozen bases answers "prime" in a fraction of a millisecond, even in Python, and were the number composite, a dozen random bases would have exposed it with probability at least . Randomized tests like this one ran the world's cryptography for decades before Agrawal, Kayal and Saxena proved in 2002 that primality can be decided deterministically in polynomial time.
What you’ll learn
- Explain why trial division is exponential in the number of digits, run the Fermat test, and prove with Korselt's criterion why Carmichael numbers such as 561 fool it for every coprime base.
- State the strong probable-prime condition behind Miller–Rabin, prove that an odd composite has at most strong liars, and use the Monier–Rabin bound to bound the error of rounds.
- Use deterministic base sets correctly, including the trap that the first 11 primes do not suffice for 64-bit integers.
- State the AKS theorem and the polynomial identity it rests on, and place it beside BPSW, ECPP certificates and the practice of generating cryptographic primes.
From trial division to Fermat
The input to a primality test is a number written with bits, so "polynomial time" means polynomial in . Trial division up to makes about divisions: exponential in the input size, hopeless for the 1,024-bit numbers of cryptography. (The sieve of Eratosthenes is the right tool for a different task: all primes up to a small bound.)
Fermat's little theorem gives a fast test. If is prime and , then . So if , the base is a Fermat witness: is certainly composite, although the test names no factor. Repeated squaring computes with multiplications of -bit numbers.
from math import gcd
def fermat_test(n, a):
"""False: a proves n composite. True: n is prime, or a is a Fermat liar for n."""
return pow(a, n - 1, n) == 1
def is_carmichael(n, primes):
"""Korselt's criterion, given the prime factors of n (with repetition)."""
return (len(primes) >= 2 and len(set(primes)) == len(primes) # composite and squarefree
and all((n - 1) % (p - 1) == 0 for p in primes))
print(fermat_test(341, 2), fermat_test(341, 3)) # True False: 341 = 11 * 31
print(is_carmichael(561, [3, 11, 17])) # True: 2, 10 and 16 all divide 560
print(sum(fermat_test(561, a) for a in range(1, 561) if gcd(a, 561) == 1)) # 320 = phi(561)Base 2 is a Fermat liar for , but base 3 exposes it (). Korselt's criterion agrees with the definition of Carmichael numbers for every ; they are 561, 1105, 1729, 2465, 2821, 6601, 8911, 10585 and 15841.
has bases coprime to it. How many of them are Fermat liars?
Show the answer
320
All 320. For each prime , the exponent 560 is a multiple of (2, 10 and 16), so for every coprime to , and by the Chinese remainder theorem . Only the 240 bases that share a factor with 561 expose it, and for Carmichael numbers with large prime factors such bases are vanishingly rare.
Miller–Rabin: square roots of 1
The fix is a fact that holds modulo primes but fails modulo most composites: if is prime and , then divides , so . One has to look at the square roots on the way to .
Write with odd, and compute the sequence by repeated squaring. For a prime the last term is 1, and the term just before the first 1 must be . So is a strong probable prime to base if or for some ; otherwise is a strong witness and is composite (Miller, 1976; Rabin, 1980).
is not a Carmichael number. Some coprime base is a Fermat witness, so the Fermat liars form a proper subgroup, of size at most . Every strong liar is a Fermat liar, since its sequence ends in 1.
is a Carmichael number, hence squarefree with at least two prime factors: write with coprime . The base is a strong liar (, as is odd), so let be the largest for which some strong liar has , and define
is a subgroup, and it contains every strong liar: a liar with , or with for some , has , and by the choice of no liar reaches later than step . By the Chinese remainder theorem choose and . Then
so is neither nor modulo (since ), and . is a proper subgroup, so it has at most half the elements:
The bound is attained: among odd composites below 6,000, the numbers 15, 91, 703 and 1891 have exactly strong liars, and 9, the exception, has 2 of 6 (the bases 1 and 8). The guarantee holds for every composite ; it says nothing special about random inputs, on which the error is far smaller (Damgård, Landrock & Pomerance, 1993).
Deterministic answers
The bound promises that most bases are witnesses for each composite, but not which ones. For numbers below a fixed limit, exhaustive computer searches have found the smallest composite that fools every base of a given set, written for the first primes. Below , the first primes give a deterministic test:
| Bases | Deterministic for all below | Remark |
|---|---|---|
| 2 | 2,047 | fools base 2 |
| 2, 3, 5, 7 | 3,215,031,751 | : enough below , but not for every unsigned 32-bit integer |
| the first 7 or 8 primes (2 to 19) | 341,550,071,728,321 | about |
| the first 9, 10 or 11 primes (2 to 31) | 3,825,123,056,546,413,051 | about , below |
| the first 12 primes (2 to 37) | 318,665,857,834,031,151,167,461 | about , covers every 64-bit integer (Sorenson & Webster, 2017) |
def is_prime(n):
"""Miller-Rabin with the first 12 primes as bases: deterministic for all
n < 318665857834031151167461 (about 3.2e23), which covers every 64-bit integer."""
if n < 2:
return False
bases = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
for p in bases:
if n % p == 0:
return n == p
d, s = n - 1, 0
while d % 2 == 0:
d //= 2; s += 1 # n - 1 = 2^s * d with d odd
for a in bases:
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue # a is a strong liar, or n is prime
for _ in range(s - 1):
x = x * x % n
if x == n - 1:
break
else:
return False # a is a strong witness: n is composite
return TrueAgrees with a sieve on every , and calls prime in about 0.1 ms. At the limit itself it fails as the table predicts: is_prime returns True for the composite 318,665,857,834,031,151,167,461. In C++, use 128-bit products (unsigned __int128, a GCC/Clang extension) for on 64-bit .
A library tests 64-bit integers with Miller–Rabin using the first 11 primes, 2 through 31, as bases. Is it correct for every 64-bit input?
- Yes: 11 bases leave an error below , which is negligible
- Yes: any 7 bases suffice below
- No: 3,825,123,056,546,413,051 is below and fools all 11 bases; adding 37 fixes it
- No: Miller–Rabin can never be deterministic
Show the answer
C. No: 3,825,123,056,546,413,051 is below and fools all 11 bases; adding 37 fixes it
lies below , so some 64-bit composite passes all of 2, 3, …, 31. With 37 added, the first composite fooling every base is , beyond 64 bits.
Three other routes to certainty:
- Special bases. Jim Sinclair found seven bases, 2, 325, 9375, 28178, 450775, 9780504 and 1795265022, that are correct for every ; reduce each base modulo and skip it if it becomes 0.
- The Riemann hypothesis. Miller (1976) showed that, if the generalized Riemann hypothesis holds, every odd composite has a strong witness of size ; Bach (1990) gave the explicit bound . Testing all such bases is a deterministic polynomial-time test, but only conditionally.
- BPSW. One strong test to base 2 combined with a strong Lucas test: no composite is known to pass it, and none exists below , though heuristic arguments suggest that counterexamples exist. Many libraries use it as their "is probably prime" test.
AKS, certificates and primes in practice
Let and . In the polynomial ring :
If is prime, every binomial coefficient with is divisible by , and by Fermat's little theorem, so only the two outer terms survive.
If is composite, take a prime with the exact power of dividing . The coefficient of is ; does not divide , and , so this coefficient is not 0 modulo and the identity fails.
Checking the identity directly means coefficients, exponentially many in . AKS checks it modulo for a small , polylogarithmic in , and for polylogarithmically many . The deep part of the paper proves that passing these few checks forces to be a prime power, which the first step rules out.
AKS(n): # n > 1
if n = a^b for integers a > 1, b > 1: return COMPOSITE
r ← the smallest r with ord_r(n) > (log2 n)^2 # r = O(log^5 n)
for a in 2 .. min(r, n - 1):
if a divides n: return COMPOSITE
if n <= r: return PRIME
for a in 1 .. floor(sqrt(phi(r)) * log2 n):
if (X + a)^n ≠ X^n + a in Z_n[X] / (X^r - 1): return COMPOSITE
return PRIMEis the multiplicative order of modulo . Each polynomial power is computed by repeated squaring on polynomials of degree below with coefficients modulo .
In practice AKS is far slower than Miller–Rabin, and nobody uses it to test numbers. When a proof of primality is required, elliptic curve primality proving (ECPP; Goldwasser & Kilian, 1986; Atkin & Morain, 1993) produces a certificate that anyone can check quickly, and it has proved numbers with tens of thousands of digits prime. Numbers of special form have special tests, such as the Lucas–Lehmer test for Mersenne numbers , the form of the largest known primes.
Generating a cryptographic prime. By the prime number theorem, a random number near is prime with probability about . For a 1,024-bit prime, draw random odd 1,024-bit numbers: about candidates are needed on average. Trial division by small primes discards most candidates cheaply, and Miller–Rabin rounds handle the survivors. Finding the factors of a composite is another matter: no polynomial-time classical factoring algorithm is known, and RSA's security rests on that belief. Pollard's rho finds a small factor in about steps (see Cycle Detection: Floyd & Brent).
Key takeaways
- Trial division takes about steps on a -bit number, exponential in the input size. Fermat's test is fast, but Carmichael numbers such as , infinitely many of them, pass it for every coprime base.
- Miller–Rabin also checks the square roots of 1 on the way to ; a subgroup argument shows that at most half of the bases lie, Monier and Rabin sharpen this to a quarter, so random rounds err with probability at most on every composite.
- Fixed bases are deterministic only below verified limits: 2, 3, 5, 7 below 3,215,031,751; the first 12 primes below about , which covers 64 bits, while the first 11 primes fail at about .
- AKS put PRIMES in P (2002) by checking modulo ; in practice Miller–Rabin, BPSW and ECPP certificates do the work, and factoring, unlike testing, has no known polynomial-time classical algorithm.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which statement about Carmichael numbers is true?
- Every base coprime to is a Fermat liar, yet Miller–Rabin still exposes with probability at least per random base
- They are strong pseudoprimes to every base, so Miller–Rabin cannot detect them either
- Only finitely many exist, so a lookup table handles them
- They are prime powers, so a perfect-power check removes them
Show the answer
A. Every base coprime to is a Fermat liar, yet Miller–Rabin still exposes with probability at least per random base
Korselt's criterion makes for every coprime , which blinds the Fermat test. The strong test also checks the square roots of 1 on the way, and the Monier–Rabin bound applies to every odd composite , Carmichael or not: at most a quarter of the bases lie. For 561, only 10 of 320 coprime bases do.
A number passes 20 Miller–Rabin rounds with independent random bases. What does the bound say?
- The number is prime with probability at least
- For any fixed composite number, the probability of passing 20 such rounds is at most
- One number in is a strong pseudoprime to 20 bases
- The number has no prime factor below
Show the answer
B. For any fixed composite number, the probability of passing 20 such rounds is at most
The probability is over the algorithm's random bases, for a fixed input. Whether "it passed, so it is prime with probability ..." also depends on how the number was chosen, which is a different, Bayesian question; for random candidates it is even more favorable.
During a Miller–Rabin round on an odd , the sequence reaches with but . What follows?
- is prime, since the sequence ended in 1
- Nothing yet: another base must be tried
- is a Carmichael number
- is composite, and is a nontrivial factor of
Show the answer
D. is composite, and is a nontrivial factor of
divides but neither factor, which is impossible for a prime. So shares a nontrivial factor with each of and : for 561 and base 2, gives and .
AKS rests on , which holds exactly when is prime (for ). Why can't the algorithm simply check this identity?
- The identity is only conjectured, not proved
- Expanding produces coefficients, exponentially many in the number of digits, so AKS checks it modulo with polylogarithmic in
- It is false for Carmichael numbers
- Polynomial arithmetic modulo is undecidable
Show the answer
B. Expanding produces coefficients, exponentially many in the number of digits, so AKS checks it modulo with polylogarithmic in
The identity is an elementary theorem, but checking it costs time proportional to , which is for bits. Reducing modulo keeps polynomials of degree below , and the hard part of the AKS paper is proving that a few such reduced checks still certify primality.
Further reading
- G. L. Miller, "Riemann's hypothesis and tests for primality," Journal of Computer and System Sciences 13(3) (1976), 300–317.
- M. O. Rabin, "Probabilistic algorithm for testing primality," Journal of Number Theory 12(1) (1980), 128–138.
- W. R. Alford, A. Granville & C. Pomerance, "There are infinitely many Carmichael numbers," Annals of Mathematics 139 (1994), 703–722.
- M. Agrawal, N. Kayal & N. Saxena, "PRIMES is in P," Annals of Mathematics 160(2) (2004), 781–793.
- J. Sorenson & J. Webster, "Strong pseudoprimes to twelve prime bases," Mathematics of Computation 86 (2017), 985–1003.