Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Primality Testing

Fermat, Miller–Rabin and the AKS theorem.

Is 289−12^{89} - 1 prime? Trial division would try about 244.5≈2.5×10132^{44.5} \approx 2.5 \times 10^{13} 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 1−4−121 - 4^{-12}. 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 φ(n)/2\varphi(n)/2 strong liars, and use the Monier–Rabin bound φ(n)/4\varphi(n)/4 to bound the error of kk 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 nn written with b≈log⁡2nb \approx \log_2 n bits, so "polynomial time" means polynomial in bb. Trial division up to n\sqrt n makes about 2b/22^{b/2} 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 pp is prime and p∤ap \nmid a, then ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p. So if an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod n, the base aa is a Fermat witness: nn is certainly composite, although the test names no factor. Repeated squaring computes an−1 mod na^{n-1} \bmod n with O(b)O(b) multiplications of bb-bit numbers.

python
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 341=11⋅31341 = 11 \cdot 31, but base 3 exposes it (3340 mod 341=563^{340} \bmod 341 = 56). Korselt's criterion agrees with the definition of Carmichael numbers for every n<20,000n < 20{,}000; they are 561, 1105, 1729, 2465, 2821, 6601, 8911, 10585 and 15841.

Predict before you look

561=3⋅11⋅17561 = 3 \cdot 11 \cdot 17 has φ(561)=320\varphi(561) = 320 bases coprime to it. How many of them are Fermat liars?

Show the answer

320

All 320. For each prime p∣561p \mid 561, the exponent 560 is a multiple of p−1p - 1 (2, 10 and 16), so a560≡1(modp)a^{560} \equiv 1 \pmod p for every aa coprime to pp, and by the Chinese remainder theorem a560≡1(mod561)a^{560} \equiv 1 \pmod{561}. 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 pp is prime and x2≡1(modp)x^2 \equiv 1 \pmod p, then pp divides (x−1)(x+1)(x-1)(x+1), so x≡±1x \equiv \pm 1. One has to look at the square roots on the way to an−1a^{n-1}.

Write n−1=2sdn - 1 = 2^s d with dd odd, and compute the sequence ad,a2d,a4d,…,a2sd=an−1a^d, a^{2d}, a^{4d}, \dots, a^{2^s d} = a^{n-1} by repeated squaring. For a prime nn the last term is 1, and the term just before the first 1 must be −1-1. So nn is a strong probable prime to base aa if ad≡1a^d \equiv 1 or a2rd≡−1a^{2^r d} \equiv -1 for some 0≤r<s0 \le r < s; otherwise aa is a strong witness and nn is composite (Miller, 1976; Rabin, 1980).

DerivationProof of the one-half bound (two cases)
  1. #{strong liars}  ≤  #{Fermat liars}  ≤  φ(n)/2\#\{\text{strong liars}\} \;\le\; \#\{\text{Fermat liars}\} \;\le\; \varphi(n)/2

    nn is not a Carmichael number. Some coprime base is a Fermat witness, so the Fermat liars form a proper subgroup, of size at most φ(n)/2\varphi(n)/2. Every strong liar is a Fermat liar, since its sequence ends in 1.

  2. B  =  { x∈Zn∗  :  x2jd≡±1(modn) }B \;=\; \{\, x \in \Z_n^* \;:\; x^{2^j d} \equiv \pm 1 \pmod n \,\}

    nn is a Carmichael number, hence squarefree with at least two prime factors: write n=n1n2n = n_1 n_2 with coprime n1,n2≥3n_1, n_2 \ge 3. The base −1-1 is a strong liar ((−1)d=−1(-1)^d = -1, as dd is odd), so let jj be the largest r<sr < s for which some strong liar vv has v2rd≡−1v^{2^r d} \equiv -1, and define

  3. w2jd≡−1(modn1),w2jd≡1(modn2)w^{2^j d} \equiv -1 \pmod{n_1}, \qquad w^{2^j d} \equiv 1 \pmod{n_2}

    BB is a subgroup, and it contains every strong liar: a liar with ad≡1a^d \equiv 1, or with a2rd≡−1a^{2^r d} \equiv -1 for some r<jr < j, has a2jd≡1a^{2^j d} \equiv 1, and by the choice of jj no liar reaches −1-1 later than step jj. By the Chinese remainder theorem choose w≡v(modn1)w \equiv v \pmod{n_1} and w≡1(modn2)w \equiv 1 \pmod{n_2}. Then

  4. #{strong liars}  ≤  ∣B∣  ≤  φ(n)/2\#\{\text{strong liars}\} \;\le\; \abs{B} \;\le\; \varphi(n)/2

    so w2jdw^{2^j d} is neither 11 nor −1-1 modulo nn (since n1,n2≥3n_1, n_2 \ge 3), and w∉Bw \notin B. BB is a proper subgroup, so it has at most half the elements:

The bound φ(n)/4\varphi(n)/4 is attained: among odd composites below 6,000, the numbers 15, 91, 703 and 1891 have exactly φ(n)/4\varphi(n)/4 strong liars, and 9, the exception, has 2 of 6 (the bases 1 and 8). The 4−k4^{-k} guarantee holds for every composite nn; it says nothing special about random inputs, on which the error is far smaller (Damgård, Landrock & Pomerance, 1993).

Deterministic answers

The bound φ(n)/4\varphi(n)/4 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 ψm\psi_m for the first mm primes. Below ψm\psi_m, the first mm primes give a deterministic test:

BasesDeterministic for all nn belowRemark
22,0472047=23⋅892047 = 23 \cdot 89 fools base 2
2, 3, 5, 73,​215,​031,​751=151⋅751⋅28351= 151 \cdot 751 \cdot 28351: enough below 2312^{31}, but not for every unsigned 32-bit integer
the first 7 or 8 primes (2 to 19)341,​550,​071,​728,​321about 3.4×10143.4 \times 10^{14}
the first 9, 10 or 11 primes (2 to 31)3,​825,​123,​056,​546,​413,​051about 3.8×10183.8 \times 10^{18}, below 264≈1.8×10192^{64} \approx 1.8 \times 10^{19}
the first 12 primes (2 to 37)318,​665,​857,​834,​031,​151,​167,​461about 3.2×10233.2 \times 10^{23}, covers every 64-bit integer (Sorenson & Webster, 2017)
Each limit is itself a strong pseudoprime to all the bases in its row (checked directly), so the test must not be trusted at or beyond it.
python
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 True

Agrees with a sieve on every n≤2×106n \le 2 \times 10^6, and calls 289−12^{89} - 1 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 x⋅x mod nx \cdot x \bmod n on 64-bit nn.

Check your understanding

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?

  1. Yes: 11 bases leave an error below 4−114^{-11}, which is negligible
  2. Yes: any 7 bases suffice below 2642^{64}
  3. No: 3,825,123,056,546,413,051 is below 2642^{64} and fools all 11 bases; adding 37 fixes it
  4. No: Miller–Rabin can never be deterministic
Show the answer

C. No: 3,825,123,056,546,413,051 is below 2642^{64} and fools all 11 bases; adding 37 fixes it

ψ11≈3.8×1018\psi_{11} \approx 3.8 \times 10^{18} lies below 264≈1.8×10192^{64} \approx 1.8 \times 10^{19}, so some 64-bit composite passes all of 2, 3, …, 31. With 37 added, the first composite fooling every base is ψ12≈3.2×1023\psi_{12} \approx 3.2 \times 10^{23}, 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 n<264n < 2^{64}; reduce each base modulo nn and skip it if it becomes 0.
  • The Riemann hypothesis. Miller (1976) showed that, if the generalized Riemann hypothesis holds, every odd composite nn has a strong witness of size O(log⁡2n)O(\log^2 n); Bach (1990) gave the explicit bound 2(ln⁡n)22 (\ln n)^2. 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 2642^{64}, though heuristic arguments suggest that counterexamples exist. Many libraries use it as their "is probably prime" test.

AKS, certificates and primes in practice

DerivationThe identity behind AKS
  1. n is prime  ⟺  (X+a)n≡Xn+a(modn)n \text{ is prime} \iff (X + a)^n \equiv X^n + a \pmod n

    Let n≥2n \ge 2 and gcd⁡(a,n)=1\gcd(a, n) = 1. In the polynomial ring (Z/nZ)[X](\Z/n\Z)[X]:

  2. (X+a)n  =  Xn+∑0<i<n(ni)an−iXi+an  ≡  Xn+a(X + a)^n \;=\; X^n + \sum_{0<i<n}\binom{n}{i}a^{n-i}X^{i} + a^n \;\equiv\; X^n + a

    If nn is prime, every binomial coefficient (ni)\binom ni with 0<i<n0 < i < n is divisible by nn, and an≡aa^n \equiv a by Fermat's little theorem, so only the two outer terms survive.

  3. qk∤(nq) an−q⟹(nq)an−q≢0(modn)q^k \nmid \binom{n}{q} \,a^{n-q} \quad\Longrightarrow\quad \binom{n}{q} a^{n-q} \not\equiv 0 \pmod n

    If nn is composite, take a prime q∣nq \mid n with qkq^k the exact power of qq dividing nn. The coefficient of XqX^q is (nq)an−q\binom nq a^{n-q}; qkq^k does not divide (nq)\binom nq, and q∤aq \nmid a, so this coefficient is not 0 modulo nn and the identity fails.

  4. (X+a)n≡Xn+a(modXr−1, n)for 1≤a≤⌊φ(r) log⁡2n⌋(X + a)^n \equiv X^n + a \pmod{X^r - 1,\ n} \quad \text{for } 1 \le a \le \big\lfloor \sqrt{\varphi(r)}\,\log_2 n \big\rfloor

    Checking the identity directly means n+1n + 1 coefficients, exponentially many in log⁡n\log n. AKS checks it modulo Xr−1X^r - 1 for a small rr, polylogarithmic in nn, and for polylogarithmically many aa. The deep part of the paper proves that passing these few checks forces nn to be a prime power, which the first step rules out.

text
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 PRIME

ordr(n)\text{ord}_r(n) is the multiplicative order of nn modulo rr. Each polynomial power is computed by repeated squaring on polynomials of degree below rr with coefficients modulo nn.

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 2p−12^p - 1, the form of the largest known primes.

Generating a cryptographic prime. By the prime number theorem, a random number near NN is prime with probability about 1/ln⁡N1/\ln N. For a 1,024-bit prime, draw random odd 1,024-bit numbers: about ln⁡(21024)/2≈355\ln(2^{1024}) / 2 \approx 355 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 pp in about p\sqrt p steps (see Cycle Detection: Floyd & Brent).

Key takeaways

  • Trial division takes about n=2b/2\sqrt n = 2^{b/2} steps on a bb-bit number, exponential in the input size. Fermat's test is fast, but Carmichael numbers such as 561=3⋅11⋅17561 = 3 \cdot 11 \cdot 17, infinitely many of them, pass it for every coprime base.
  • Miller–Rabin also checks the square roots of 1 on the way to an−1a^{n-1}; a subgroup argument shows that at most half of the bases lie, Monier and Rabin sharpen this to a quarter, so kk random rounds err with probability at most 4−k4^{-k} 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 3.2×10233.2 \times 10^{23}, which covers 64 bits, while the first 11 primes fail at about 3.8×10183.8 \times 10^{18}.
  • AKS put PRIMES in P (2002) by checking (X+a)n≡Xn+a(X + a)^n \equiv X^n + a modulo Xr−1X^r - 1; 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.

Question 1

Which statement about Carmichael numbers is true?

  1. Every base coprime to nn is a Fermat liar, yet Miller–Rabin still exposes nn with probability at least 3/43/4 per random base
  2. They are strong pseudoprimes to every base, so Miller–Rabin cannot detect them either
  3. Only finitely many exist, so a lookup table handles them
  4. They are prime powers, so a perfect-power check removes them
Show the answer

A. Every base coprime to nn is a Fermat liar, yet Miller–Rabin still exposes nn with probability at least 3/43/4 per random base

Korselt's criterion makes an−1≡1a^{n-1} \equiv 1 for every coprime aa, 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 n≠9n \ne 9, Carmichael or not: at most a quarter of the bases lie. For 561, only 10 of 320 coprime bases do.

Question 2

A number passes 20 Miller–Rabin rounds with independent random bases. What does the bound 4−204^{-20} say?

  1. The number is prime with probability at least 1−4−201 - 4^{-20}
  2. For any fixed composite number, the probability of passing 20 such rounds is at most 4−204^{-20}
  3. One number in 4204^{20} is a strong pseudoprime to 20 bases
  4. The number has no prime factor below 4204^{20}
Show the answer

B. For any fixed composite number, the probability of passing 20 such rounds is at most 4−204^{-20}

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.

Question 3

During a Miller–Rabin round on an odd nn, the sequence reaches xx with x≢±1x \not\equiv \pm 1 but x2≡1(modn)x^2 \equiv 1 \pmod n. What follows?

  1. nn is prime, since the sequence ended in 1
  2. Nothing yet: another base must be tried
  3. nn is a Carmichael number
  4. nn is composite, and gcd⁡(x−1,n)\gcd(x - 1, n) is a nontrivial factor of nn
Show the answer

D. nn is composite, and gcd⁡(x−1,n)\gcd(x - 1, n) is a nontrivial factor of nn

nn divides (x−1)(x+1)(x-1)(x+1) but neither factor, which is impossible for a prime. So nn shares a nontrivial factor with each of x−1x - 1 and x+1x + 1: for 561 and base 2, x=67x = 67 gives gcd⁡(66,561)=33\gcd(66, 561) = 33 and gcd⁡(68,561)=17\gcd(68, 561) = 17.

Question 4

AKS rests on (X+a)n≡Xn+a(modn)(X + a)^n \equiv X^n + a \pmod n, which holds exactly when nn is prime (for gcd⁡(a,n)=1\gcd(a, n) = 1). Why can't the algorithm simply check this identity?

  1. The identity is only conjectured, not proved
  2. Expanding (X+a)n(X + a)^n produces n+1n + 1 coefficients, exponentially many in the number of digits, so AKS checks it modulo Xr−1X^r - 1 with rr polylogarithmic in nn
  3. It is false for Carmichael numbers
  4. Polynomial arithmetic modulo nn is undecidable
Show the answer

B. Expanding (X+a)n(X + a)^n produces n+1n + 1 coefficients, exponentially many in the number of digits, so AKS checks it modulo Xr−1X^r - 1 with rr polylogarithmic in nn

The identity is an elementary theorem, but checking it costs time proportional to nn, which is 2b2^b for bb bits. Reducing modulo Xr−1X^r - 1 keeps polynomials of degree below rr, 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.