The Miller-Rabin Test and Probably Prime Numbers
Learn the Miller-Rabin primality test step by step, with checked examples and a clear account of what probably prime really means.
Key takeaways
- A "composite" verdict from Miller-Rabin is always correct; only a "probably prime" verdict carries any doubt.
- The test rests on the fact that modulo a prime, the only square roots of 1 are 1 and −1.
- For any odd composite n greater than 9, at most one quarter of the bases from 1 to n − 1 can fool it.
- With k independent random bases, a composite number survives with probability at most 1 in 4ᵏ.
- For numbers below fixed limits, certain short lists of bases give a completely certain answer.
The Miller-Rabin test takes an odd number n and a chosen base a, then performs a short calculation with powers of a. If the result breaks a rule that every prime obeys, n is certainly composite. If it does not, n passes that round, and after many rounds with random bases you can treat it as prime with great confidence.
It is one of the most widely used algorithms in computing, because it is quick, simple to state and comes with a proven guarantee about how often it can be fooled.
Two facts about primes
The first fact is Fermat's little theorem. If p is prime and a is not a multiple of p, then a^(p−1) leaves remainder 1 on division by p.
The second concerns square roots of 1. Suppose x² leaves remainder 1 modulo a prime p. Then p divides x² − 1, which equals (x − 1)(x + 1). A prime that divides a product must divide one of the factors. So x is 1 or −1 modulo p.
Composite moduli can have more roots. Modulo 15, the numbers 1, 4, 11 and 14 all square to 1. Finding such an extra root is proof that the modulus is not prime. If the notation ≡ is new, read the introduction to modular arithmetic first.
The test itself
Take an odd n greater than 2. Divide n − 1 by 2 as many times as possible, so that n − 1 = 2ˢ × d with d odd. Pick a base a between 2 and n − 2.
Now look at this sequence, reducing each term modulo n. Each term is the square of the one before.
a^d, a^(2d), a^(4d), ..., a^(2ˢd) = a^(n−1) If n is prime, the last term is 1. Walk backward from that 1: each earlier term is a square root of the next. So either every term is 1 from the start, or somewhere there is a −1 immediately before the 1s begin.
That gives the rule. The number n passes for base a if a^d ≡ 1, or if one of a^(2ʳd), for r from 0 to s − 1, is ≡ −1. Otherwise a is a witness, and n is composite.
A composite number caught: 561
The number 561 equals 3 × 11 × 17. It is a Carmichael number, so the plain Fermat test is fooled by every base coprime to it. Miller-Rabin with base 2 is not.
Here 560 = 16 × 35, so s = 4 and d = 35.
2³⁵ ≡ 263 (mod 561)
2⁷⁰ ≡ 263² ≡ 166
2¹⁴⁰ ≡ 166² ≡ 67
2²⁸⁰ ≡ 67² ≡ 1 The first term is not 1, and −1, which is 560, never appears. So 561 is composite. Better still, 67 is a square root of 1 that is neither 1 nor −1. Taking greatest common divisors of 561 with 66 and 68 gives 33 and 17, actual factors, found by the Euclidean algorithm.
Such a lucky factorization happens for some inputs, but for a large number built from two large primes the test usually reports "composite" without revealing any factor.
A prime that passes: 97
Here 96 = 32 × 3, so s = 5 and d = 3. Use base 5.
5³ = 125 ≡ 28
5⁶ ≡ 28² ≡ 8
5¹² ≡ 8² = 64
5²⁴ ≡ 64² ≡ 22
5⁴⁸ ≡ 22² ≡ 96 ≡ −1 We reached −1, so 97 passes for base 5. One pass is not a proof, although in this tiny case trial division by 2, 3, 5 and 7 confirms that 97 is prime.
Liars and witnesses: 221
A composite n that passes for base a is a strong pseudoprime to that base, and a is called a strong liar. Take n = 221 = 13 × 17, where 220 = 4 × 55.
base 174: 174⁵⁵ ≡ 47, 174¹¹⁰ ≡ 220 ≡ −1 passes (a liar)
base 137: 137⁵⁵ ≡ 188, 137¹¹⁰ ≡ 205 composite (a witness) One unlucky base says nothing, but another settles the matter. The whole strategy is to make bad luck repeatedly improbable.
Another well-known case is 2047 = 23 × 89, the smallest strong pseudoprime to base 2. It passes because 2¹¹ leaves remainder 1 modulo 2047 and 11 divides the odd part 1023.
The one-quarter guarantee
Michael Rabin and, independently, Louis Monier proved around 1980 that for an odd composite n greater than 9, the strong liars make up at most a quarter of the numbers from 1 to n − 1. There are no exceptional composites that fool most bases, which is the crucial improvement over the Fermat test.
So choose k bases independently and at random.
| rounds k | chance a given composite survives all rounds |
|---|---|
| 1 | at most 1/4 |
| 5 | at most 1/1,024 |
| 20 | at most about 1 in a trillion |
| 40 | at most about 1 in 10²⁴ |
These are worst-case bounds. For a typical composite the liars are far rarer than a quarter.
What "probably prime" does and does not mean
Read the guarantee carefully. It says that if n is composite, it is unlikely to pass. It does not say directly that a number that passed is composite with that same probability. A fixed number is either prime or not.
The second kind of statement depends on how the number was chosen. If you pick large odd numbers at random and keep the first that passes, you must weigh how rare primes are against how rare liars are. Analyses of this situation show that for large random numbers, the actual risk is far smaller than 1/4 per round.
The picture changes if someone else hands you the number. An adversary can construct composites that pass for particular, predictable bases. That is why software handling untrusted input uses random bases and enough rounds.
Certainty for smaller numbers
For bounded inputs you can replace chance with exhaustive verification. Computer searches have found the smallest composite that fools various sets of bases.
| if n is below | passing these bases proves n prime |
|---|---|
| 2,047 | 2 |
| 1,373,653 | 2 and 3 |
| 3,215,031,751 | 2, 3, 5 and 7 |
| 2⁶⁴ | the first twelve primes, 2 through 37 |
Choose bases smaller than n, and handle small primes separately.
Gary Miller's original 1976 version was deterministic: it tried every base up to a limit proportional to (ln n)². It is correct if a generalization of the Riemann hypothesis is true. Rabin replaced the unproved assumption with random choice.
The algorithm in outline
input: odd n > 3, number of rounds k
write n − 1 = 2ˢ × d with d odd
repeat k times:
choose a at random from 2 to n − 2
x = a^d mod n
if x = 1 or x = n − 1: continue to next round
repeat s − 1 times:
x = x² mod n
if x = n − 1: leave this inner loop
if x is not n − 1: report COMPOSITE
report PROBABLY PRIME Each round costs about as much as one modular exponentiation, so numbers with hundreds of digits are handled quickly. For real security work, use a maintained cryptographic library, which also deals with randomness and subtle implementation risks.
Why the squaring chain catches so much
It is worth seeing why watching the intermediate values helps. The Fermat test looks only at the final term, a^(n−1). A composite number can easily produce a 1 there by accident of structure, and Carmichael numbers do so for every coprime base.
But to end at 1 while being composite, the chain has to get there somehow. Suppose n has two different odd prime factors p and q. Modulo n, there are then at least four square roots of 1: the numbers that are 1 or −1 modulo p, combined freely with 1 or −1 modulo q. The Chinese remainder theorem shows how each combination corresponds to one remainder modulo n.
For a base to pass, the chain modulo p and the chain modulo q must reach −1 at exactly the same step, or both be 1 from the start. These two chains behave largely independently, so such synchronization is uncommon. In the 221 example, a liar is a base whose two chains happen to line up.
Powers of a single prime, such as 25 or 343, have only the two ordinary square roots of 1. They are caught by the other half of the test, because very few bases satisfy the final Fermat condition for them.
Implementation pitfalls
The mathematics is short, but programs can still go wrong.
Overflow. Squaring a number close to n produces a value close to n². With fixed-width integers this can silently wrap around and corrupt the verdict. Use arbitrary-precision integers or a wider intermediate type.
Small and even inputs. The splitting step assumes an odd n greater than 3. Handle 0, 1, 2, 3 and even numbers before the main loop. Remember that 1 is not prime.
Degenerate bases. The bases 1 and n − 1 always pass, so they carry no information. A base that is a multiple of n gives a power of 0 and would wrongly condemn a prime. Reduce the base first and skip it if the result is 0, 1 or n − 1.
Predictable randomness. If an attacker can guess the bases, the probability argument no longer protects you.
Too few rounds for the purpose. The appropriate number depends on whether the input might be hostile and on how costly a false answer would be. Published standards give guidance for cryptographic key generation, and they are revised over time.
Where it fits among other tests
Miller-Rabin is the usual screening tool described in the overview of primality testing. When a proof is required, programs follow it with a certificate method such as elliptic curve primality proving. The logic is efficient: failed candidates are discarded at once, and the expensive proof is attempted only on a number that is almost surely prime.