Miller–Rabin Primality Test
Statement
Fermat's compositeness witness. If is prime and , then Fermat's little theorem gives . The contrapositive:
Such an is called a Fermat witness for the compositeness of .
Carmichael numbers. There exist composite (Carmichael numbers) for which for every with . The smallest is . The Miller–Rabin test strengthens Fermat's test to eliminate Carmichael numbers by additionally checking square roots of .
Visualization
Test (Carmichael number) with base :
Write . Compute the sequence modulo :
2^35 mod 561 = 263
2^70 mod 561 = 166 (263^2 mod 561)
2^140 mod 561 = 67 (166^2 mod 561)
2^280 mod 561 = 1 (67^2 mod 561)
2^560 mod 561 = 1 (1^2 mod 561)
The final value is (Fermat test passes), but and . This is a non-trivial square root of , impossible modulo a prime — so Miller–Rabin correctly rejects .
For comparison, test (prime) with :
and the sequence hits before — consistent with primality.
Carmichael witness table for :
| Property | Value |
|---|---|
| , | |
| , | |
| Fermat test | (passes — false!) |
| Miller–Rabin verdict | COMPOSITE (non-trivial sqrt of 1) |
Proof Sketch
-
Fermat witness. If is prime and , Fermat's little theorem says . Contrapositive: certifies is composite.
-
Square root argument. In for prime , the only solutions to are . So in the sequence , the first must be preceded by (or the sequence starts at ).
-
Carmichael numbers fail this. Since is composite, may have more square roots of . Detecting them certifies compositeness.
-
Probabilistic guarantee. For a random composite , at least of bases are Miller–Rabin witnesses. Running rounds gives error probability .
Connections
Miller–Rabin rests on Fermat's Little TheoremFermat's Little TheoremFor prime p, a^p is congruent to a mod pRead more → (the prime case). The square-root-of- argument uses that is a field; compare with Wilson's TheoremWilson's TheoremA natural number p > 1 is prime if and only if (p-1)! ≡ -1 mod pRead more → which characterises primes via . Large primes are generated for RSA CorrectnessRSA CorrectnessDecryption recovers the plaintext: m^(ed) ≡ m (mod n) whenever ed ≡ 1 (mod φ(n)).Read more → using exactly this test.
Lean4 Proof
/-- Fermat's compositeness witness: if n is prime then a^(n-1) ≡ 1 mod n
(for gcd(a,n)=1). We state the contrapositive concretely. -/
-- In ZMod p (prime p), every nonzero element satisfies a^(p-1) = 1.
theorem fermat_prime_pow (p : ℕ) [Fact p.Prime] {a : ZMod p} (ha : a ≠ 0) :
a ^ (p - 1) = 1 :=
ZMod.pow_card_sub_one_eq_one ha
/-- Concrete check: 561 is composite. -/
example : ¬ Nat.Prime 561 := by decide
/-- 2^560 mod 561 = 1 (Fermat test passes — 561 is a Carmichael number). -/
example : 2 ^ 560 % 561 = 1 := by decide
/-- But 2^140 mod 561 ≠ 1 and ≠ 560 (i.e. ≠ -1 mod 561).
This is the non-trivial square root of 1 that Miller–Rabin detects. -/
example : 2 ^ 140 % 561 = 67 := by decide
example : (67 : ℕ) ≠ 1 := by decide
example : (67 : ℕ) ≠ 560 := by decide