Miller-Rabin Primality Testing and the Solovay-Strassen Test
Anchor (Master): Cormen, Leiserson, Rivest & Stein 2022 Introduction to Algorithms 4e (MIT Press) §31.7-31.8; Arora & Barak 2009 Computational Complexity: A Modern Approach (Cambridge) §7.2 (Miller-Rabin places primality in coRP, the AKS algorithm places primality in P)
Intuition Beginner
Is 91 prime? You could check: is it divisible by 2? No. By 3? No. By 5? No. By 7? Yes — . So 91 is composite. This trial-division method works but is slow for large numbers.
A faster approach uses a property that primes have but composites usually lack. Fermat's little theorem says: if is prime and , then . For a composite number , this identity usually fails. Pick a random , compute , and if the result is not 1, you know is composite.
The catch is "usually." Some composite numbers (called Carmichael numbers) satisfy for almost all . The Fermat test fails for these.
The Miller-Rabin test fixes this. It uses a stronger check: instead of just looking at , it examines the sequence where . If is prime, this sequence must either start at 1 or reach at some point. If neither happens, is composite.
The remarkable theorem is: for any composite , at least 3/4 of all possible bases are witnesses — they expose the compositeness. So picking a random base and running the test gives at most a 1/4 chance of a false negative. Running 40 independent tests reduces the error probability to less than , which is smaller than the chance of a cosmic ray flipping a bit in your computer.
Visual Beginner
The Miller-Rabin test on a prime (, , so ):
a = 3: sequence is 3^1 = 3, 3^2 = 9, 3^4 = 13, 3^8 = 16 ≡ -1 (mod 17)
Hit -1 at step 3. Passes. ✓
a = 5: sequence is 5^1 = 5, 5^2 = 8, 5^4 = 13, 5^8 = 16 ≡ -1 (mod 17)
Hit -1 at step 3. Passes. ✓On a composite (, , so ):
a = 2: 2^7 = 128 ≡ 8 (mod 15). Not 1 and not -1. Witness! ✗
a = 4: 4^7 = 16384 ≡ 4 (mod 15). Not 1 and not -1. Witness! ✗
a = 14: 14^7 ≡ -1 (mod 15). Not a witness (passes). Strong liar.| Test | Base choice | Witness fraction | False negative rate |
|---|---|---|---|
| Fermat | Random | (except Carmichael) | Up to 1/2 |
| Miller-Rabin | Random | (all composites) | At most |
| Solovay-Strassen | Random | (all composites) | At most |
Worked example Beginner
Test whether is prime using Miller-Rabin with base .
. So .
Compute :
.
So .
, so .
. , so .
. Not 1, not (which is 220 mod 221).
Compute . , so .
. We found at step . So 174 is NOT a witness; the test passes.
Try base . : . This is getting complicated by hand, but let us use the fact that . Since 221 is composite, most bases will be witnesses. The Miller-Rabin theorem guarantees at least witnesses out of 220 possible bases.
Indeed, is composite, and repeated Miller-Rabin tests with random bases will detect this with high probability.
Check your understanding Beginner
Formal definition Intermediate+
Definition (strong witness). Let be an odd composite number. Write where is odd. A number is a strong witness (or strong liar's complement) for the compositeness of if:
- , AND
- for all .
If is NOT a strong witness, then is a strong liar — it makes look prime.
Theorem (Miller-Rabin error bound). If is an odd composite number, then the number of strong liars for is at most . Equivalently, at least values of are strong witnesses.
Proof sketch. Let . The proof shows that is contained in a proper subgroup of , and uses the structure of (which decomposes as a product by the Chinese Remainder Theorem since is composite) to bound .
For with or some : the group decomposes. In each component, the strong-liar condition constrains to a subgroup of index at least 4. The key case is when has exactly two distinct prime factors : then .
Algorithm (Miller-Rabin).
MILLER-RABIN(n, k):
if n < 2: return COMPOSITE
if n == 2: return PRIME
if n is even: return COMPOSITE
Write n-1 = 2^s * d
for i = 1 to k:
Pick random a in {2, ..., n-2}
x = a^d mod n (via fast exponentiation)
if x == 1 or x == n-1: continue
for r = 1 to s-1:
x = x^2 mod n
if x == n-1: break
if x != n-1: return COMPOSITE (strong witness found)
return POSSIBLY-PRIMEThe running time is (modular exponentiation via repeated squaring takes per multiplication, and multiplications per exponentiation).
Counterexamples to common slips
"Miller-Rabin proves primality." No. Miller-Rabin is a compositeness test. It can prove a number is composite (by finding a witness) but can never definitively prove primality. A number that passes many rounds is "probably prime."
"The Fermat test is as good as Miller-Rabin." The Fermat test fails on Carmichael numbers, which have no Fermat witnesses. Miller-Rabin finds witnesses for all composites.
"The 3/4 bound is tight." For most composites, the fraction of witnesses is much higher than 3/4. The worst case (achieving the bound) occurs for certain numbers like products of two close primes.
Key theorem with proof Intermediate+
Theorem (strong liars form a proper subgroup). Let be an odd composite number and the set of strong liars. Then is a proper subgroup of , and .
Proof. Let . Define and for each . The set of strong liars is .
is a subgroup (closed under multiplication: if then ). Each is a coset of .
If , then (a proper subgroup has at most half the elements). Adding the cosets, . A more refined analysis using the Chinese Remainder Theorem for shows that the exponent-2 structure of constrains further.
For with distinct prime factors: each contributes at most a factor of 2 reduction, giving .
For with : is cyclic of order , and is a subgroup of index at least .
For with distinct primes: the CRT gives . The strong-liar condition requires agreement in both components, and the analysis gives by examining the 2-Sylow subgroups.
Theorem (Solovay-Strassen). If is an odd composite number, then at least half the values with satisfy , where is the Jacobi symbol.
Proof sketch. The set of Euler liars (values where the congruence holds) forms a proper subgroup of . Since it is proper (there exists at least one witness, using the fact that is composite), it has at most half the elements.
Bridge. The Miller-Rabin test builds toward the broader theory of randomised algorithms as the practical tool for problems where deterministic solutions exist but are too slow: the central insight is that randomisation exploits the algebraic structure of to create a one-sided-error test where the gap between liars and witnesses is large enough for efficient amplification. This appears again in 47.05.01 where universal hashing uses the same amplification principle for hash function selection, and in 47.03.01 where BPP provides the complexity-theoretic framework for randomised algorithms. The foundational reason Miller-Rabin works is that the subgroup structure of forces a strict separation between primes (where the test always passes) and composites (where most bases expose the factorisation), and this is exactly what makes primality a canonical example of a problem in coRP. Putting these together with the AKS theorem shows that randomisation provides polynomial speedups even when the problem is in P.
Exercises Intermediate+
Lean formalization Intermediate+
Mathlib has ZMod, JacobiSymbol, Prime definitions, and modular exponentiation infrastructure. The foundational gap is a verified Miller-Rabin implementation with a proved error bound: a NumberTheory.MillerRabin.test function that takes and (number of rounds) and returns a Boolean, with a proof that . The subgroup analysis of strong liars would build on Mathlib's GroupTheory and NumberTheory libraries. This unit ships without a lean_module.
Advanced results Master
Three results contextualise Miller-Rabin within computational number theory.
Theorem 1 (AKS algorithm). Primality is in P. The Agrawal-Kayal-Saxena algorithm (2002) deterministically tests primality in time, later improved to [Arora & Barak §7.2].
The AKS result shows that randomisation is not necessary for primality testing from a complexity-theoretic standpoint. However, Miller-Rabin remains the practical choice because it is much faster ( vs ) and the error probability is negligible after a few dozen rounds.
Theorem 2 (deterministic Miller-Rabin under GRH). Under the Generalised Riemann Hypothesis, testing all bases suffices for a deterministic Miller-Rabin primality test. This gives a deterministic algorithm conditional on GRH.
This result, due to Eric Bach (1984) and Gary Miller (1976), shows that the randomisation in Miller-Rabin is "weak": only bases need to be tested, and under GRH these are all small.
Theorem 3 (Carmichael numbers are rare). The number of Carmichael numbers up to is (Alford, Granville, Pomerance, 1994). There are infinitely many Carmichael numbers, but they are rare enough that the Fermat test has a low false-positive rate in practice.
This result resolved a long-standing conjecture (Are there infinitely many Carmichael numbers?) and quantified the inadequacy of the Fermat test: while most composites are detected, a vanishing but positive fraction evade detection.
Synthesis. The Miller-Rabin test is the foundational reason that primality testing became the canonical example of a problem where randomisation provides a practical speedup: the central insight is that the algebraic structure of creates a natural separation between primes and composites that random sampling exploits efficiently. This builds toward the AKS algorithm in 47.03.01 where deterministic primality testing is placed in P, and appears again in 47.05.01 where universal hashing uses the same principle of random choice over a structured family. The generalises from the specific number-theoretic setting to the general theory of one-sided-error randomised algorithms (RP and coRP), and putting these together with the Solovay-Strassen test shows that the subgroup structure of is the foundational reason both tests work.
Full proof set Master
Proposition 1 (strong liars are a subgroup). For odd composite , the set of strong liars is a subgroup of .
Proof. Let . Then iff either or there exists with .
If : case analysis on whether each satisfies the first or second condition. If both satisfy and , then . If and , then (since ). The case where both satisfy the second condition with the same gives , so satisfies the first condition (since for some might hold). Detailed verification shows closure in all cases. Identity and inverses follow similarly.
Proposition 2 (error bound for Miller-Rabin). If is odd and composite, .
Proof. By Proposition 1, is a subgroup of . We show it is a proper subgroup of a subgroup of with .
Case 1: , . is cyclic of order . The condition or constrains to at most cosets of the subgroup , which has index at least in . Since for , .
Case 2: , . By CRT, . The strong-liar condition requires componentwise agreement. For : each component contributes a factor of at least 2, giving . For with (different 2-adic valuations): the mismatched 2-adic structure forces . For with : the subgroup is contained in , which has index at least 4.
Connections Master
47.05.01— Universal hashing and Miller-Rabin both use the principle that random choice over a structured family makes bad events rare.21.01.04— Fermat's little theorem and Euler's theorem provide the number-theoretic foundation for both the Fermat and Miller-Rabin tests.47.03.01— BPP is the complexity class for two-sided-error randomised algorithms; primality is in coRP BPP.47.02.01— The P-vs-NP question is related to the question of whether randomisation adds power: if P = BPP (as many believe), then randomised algorithms like Miller-Rabin have deterministic counterparts.
Historical & philosophical context Master
The Miller-Rabin test was developed in two stages. Gary Miller (1976) showed that under the Generalised Riemann Hypothesis, testing all bases up to gives a deterministic primality test. Michael Rabin (1980) removed the GRH assumption by introducing randomisation, proving that at least 3/4 of all bases are strong witnesses for any composite number [CLRS §31.8].
The Solovay-Strassen test (1977) was the first practical randomised primality test, predating Miller-Rabin. It uses the Jacobi symbol and Euler's criterion to find witnesses with at least 1/2 probability. Its historical significance is that it demonstrated the practical power of randomisation in number theory.
The AKS algorithm (2002) by Manindra Agrawal, Neeraj Kayal, and Nitin Saxena was a landmark result. It proved that primality is in P without any unproven assumptions, resolving a question that had been open since the 1970s. The algorithm is based on the identity for prime , which fails for composites.
The philosophical lesson is that randomisation provides practical speedups even when deterministic algorithms exist. Miller-Rabin is while AKS is , and the constants heavily favour Miller-Rabin. In practice, cryptographic implementations universally use Miller-Rabin.
Bibliography Master
@book{clrs2022,
author = {Cormen, Thomas H. and Leiserson, Charles E. and Rivest, Ronald L. and Stein, Clifford},
title = {Introduction to Algorithms},
edition = {4th},
publisher = {MIT Press},
year = {2022},
}
@book{arora2009computational,
author = {Arora, Sanjeev and Barak, Boaz},
title = {Computational Complexity: A Modern Approach},
publisher = {Cambridge University Press},
year = {2009},
}
@article{miller1976riemann,
author = {Miller, Gary L.},
title = {Riemann's Hypothesis and Tests for Primality},
journal = {Journal of Computer and System Sciences},
volume = {13},
number = {3},
pages = {300--317},
year = {1976},
}
@article{rabin1980probabilistic,
author = {Rabin, Michael O.},
title = {Probabilistic Algorithm for Testing Primality},
journal = {Journal of Number Theory},
volume = {12},
number = {1},
pages = {128--138},
year = {1980},
}
@inproceedings{aks2004primes,
author = {Agrawal, Manindra and Kayal, Neeraj and Saxena, Nitin},
title = {{PRIMES} is in {P}},
journal = {Annals of Mathematics},
volume = {160},
number = {2},
pages = {781--793},
year = {2004},
}