Miller-Rabin: Error Bound and Cost
Is a 1024-bit number prime? Trial division up to its square root would take about divisions, far beyond any computer. The Miller-Rabin test answers in a few hundred modular multiplications, with an error probability that can be made smaller than the chance of a hardware fault. It is a Monte Carlo algorithm: when it says "composite" it is always right, and when it says "prime" it is wrong with probability at most after independent rounds. This lesson presents the test as an algorithm, measures how often a single round is fooled, and counts its cost. The proofs of the number theory behind it are in The Miller-Rabin Test.
From Fermat to Miller-Rabin
Fermat's little theorem says for a prime and every with . A base with is a proof that is composite. Unfortunately some composites, the Carmichael numbers ( is the smallest), pass the Fermat test for every base coprime to them (Carmichael Numbers).
Miller-Rabin adds a second check. Modulo a prime, the only square roots of 1 are and . Write with odd and compute the sequence
If is prime, either , or some with (the last value before the sequence reaches 1 must be ). If neither happens, is a witness: it proves composite, either through Fermat () or through a nontrivial square root of 1 (some with ).
WITNESS(a, n) // true if a proves the odd number n > 2 composite
1 write n - 1 = 2^t * u with u odd
2 x = MODULAR-EXPONENTIATION(a, u, n)
3 if x == 1 or x == n - 1
4 return false
5 for i = 1 to t - 1
6 x = x * x mod n
7 if x == n - 1
8 return false
9 return true // never reached -1: nontrivial root of 1 or Fermat failure
MILLER-RABIN(n, s)
1 for j = 1 to s
2 a = RANDOM(2, n - 2)
3 if WITNESS(a, n)
4 return "composite" // always correct
5 return "probably prime"The program traces the base 7 on the Carmichael number 561, where Fermat is fooled but the square-root check is not.
def witness_trace(a, n):
t, u = 0, n - 1
while u % 2 == 0:
t, u = t + 1, u // 2
xs = [pow(a, u, n)]
for _ in range(t):
xs.append(xs[-1] * xs[-1] % n)
print(f"n - 1 = {n - 1} = 2^{t} * {u}; x_0 .. x_{t} = {xs}")
return xs
xs = witness_trace(7, 561)
print("Fermat test: 7^560 mod 561 =", xs[-1], "-> fooled")
i = xs.index(1)
print(f"but x_{i - 1} = {xs[i - 1]} squares to 1 and is not 1 or 560: a nontrivial square root of 1")
print("so 561 is composite; indeed gcd(67 - 1, 561) =", __import__("math").gcd(66, 561),
"and gcd(67 + 1, 561) =", __import__("math").gcd(68, 561))n - 1 = 560 = 2^4 * 35; x_0 .. x_4 = [241, 298, 166, 67, 1]
Fermat test: 7^560 mod 561 = 1 -> fooled
but x_3 = 67 squares to 1 and is not 1 or 560: a nontrivial square root of 1
so 561 is composite; indeed gcd(67 - 1, 561) = 33 and gcd(67 + 1, 561) = 17
A nontrivial square root of 1 even reveals factors: divides but neither factor, so are proper divisors.
How often is one round fooled?
A base that fails to be a witness for a composite is a strong liar. The key theorem:
Theorem (Monier, Rabin, 1980). For every odd composite , at most of the bases are strong liars.
(CLRS-style textbooks often prove the simpler bound of one half; the quarter needs more group theory.) So one round with a random base errs with probability below , and independent rounds with probability below . The program counts the strong liars of some odd composites exactly, next to the Fermat liars.
from math import gcd
def is_witness(a, n):
t, u = 0, n - 1
while u % 2 == 0:
t, u = t + 1, u // 2
x = pow(a, u, n)
if x in (1, n - 1):
return False
for _ in range(t - 1):
x = x * x % n
if x == n - 1:
return False
return True
print(" n factors strong liars fraction Fermat liars")
for n, f in [(91, "7 * 13"), (341, "11 * 31"), (561, "3 * 11 * 17"), (1105, "5 * 13 * 17"),
(8911, "7 * 19 * 67"), (703, "19 * 37"), (2047, "23 * 89")]:
strong = sum(1 for a in range(1, n) if not is_witness(a, n))
fermat = sum(1 for a in range(1, n) if pow(a, n - 1, n) == 1)
print(f"{n:6} {f:14} {strong:14} {strong / (n - 1):10.4f} {fermat:14}")
worst = max(((sum(1 for a in range(1, n) if not is_witness(a, n)) / (n - 1), n)
for n in range(11, 1500, 2) if any(n % p == 0 for p in range(3, int(n ** 0.5) + 1, 2))))
print(f"worst fraction among odd composites 11 .. 1499: {worst[0]:.4f} at n = {worst[1]}") n factors strong liars fraction Fermat liars
91 7 * 13 18 0.2000 36
341 11 * 31 50 0.1471 100
561 3 * 11 * 17 10 0.0179 320
1105 5 * 13 * 17 30 0.0272 768
8911 7 * 19 * 67 1782 0.2000 7128
703 19 * 37 162 0.2308 324
2047 23 * 89 242 0.1183 484
worst fraction among odd composites 11 .. 1499: 0.2308 at n = 703
The Carmichael numbers fool the Fermat test for every base coprime to them (320 of 560 bases for 561), but far fewer bases are strong liars: only 10 for 561. The worst fraction found stays below ; the bound is nearly reached by numbers of the form with both factors prime, such as .
Cost
One round is one modular exponentiation with exponent plus at most squarings, together at most about modular multiplications for a -bit , so bit operations with schoolbook arithmetic (Modular Exponentiation and Its Bit Cost). With rounds:
Forty rounds push the error below . For random inputs the actual error is far smaller still, because most composites have very few strong liars. For bounded , fixed bases give a deterministic test: the bases are correct for all , and the first twelve primes as bases for all below about . Since 2002 primality is also known to be in P deterministically (the AKS test), but Miller-Rabin remains the practical choice.
def miller_rabin(n, bases):
if n < 2:
return False
for p in (2, 3, 5, 7):
if n % p == 0:
return n == p
t, u = 0, n - 1
while u % 2 == 0:
t, u = t + 1, u // 2
mults = 0
for a in bases:
if a % n == 0:
continue
x = pow(a, u, n); mults += u.bit_length() + bin(u).count("1") - 2
if x in (1, n - 1):
continue
for _ in range(t - 1):
x = x * x % n; mults += 1
if x == n - 1:
break
else:
return False
return True
limit = 100_000
sieve = bytearray([1]) * limit
sieve[0] = sieve[1] = 0
for i in range(2, int(limit ** 0.5) + 1):
if sieve[i]:
sieve[i * i::i] = bytearray(len(range(i * i, limit, i)))
mr = sum(miller_rabin(n, (2, 7, 61)) for n in range(limit))
print(f"primes below {limit}: sieve {sum(sieve)}, Miller-Rabin with bases 2, 7, 61: {mr}")
p = 2**127 - 1
print("2^127 - 1 prime:", miller_rabin(p, (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)))
print("2^127 + 1 prime:", miller_rabin(2**127 + 1, (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)))primes below 100000: sieve 9592, Miller-Rabin with bases 2, 7, 61: 9592
2^127 - 1 prime: True
2^127 + 1 prime: False
In C++
The deterministic version for 32-bit numbers in C++ (bases 2, 7, 61, products in 64 bits), counting the primes below one million and checking a few famous numbers.
#include <cstdint>
#include <cstdio>
#include <initializer_list>
uint64_t power_mod(uint64_t a, uint64_t b, uint64_t m) {
uint64_t r = 1; a %= m;
for (; b; b >>= 1, a = a * a % m) if (b & 1) r = r * a % m;
return r;
}
bool is_prime(uint32_t n) {
if (n < 2) return false;
for (uint32_t p : {2u, 3u, 5u, 7u}) if (n % p == 0) return n == p;
uint32_t u = n - 1; int t = 0;
while (u % 2 == 0) { u /= 2; t++; }
for (uint64_t a : {2u, 7u, 61u}) {
if (a % n == 0) continue;
uint64_t x = power_mod(a, u, n);
if (x == 1 || x == n - 1) continue;
bool composite = true;
for (int i = 1; i < t && composite; i++) {
x = x * x % n;
if (x == n - 1) composite = false;
}
if (composite) return false;
}
return true;
}
int main() {
int count = 0;
for (uint32_t n = 0; n < 1000000; n++) count += is_prime(n);
std::printf("primes below 10^6: %d\n", count);
for (uint32_t n : {561u, 1105u, 2147483647u, 4294967291u, 4294967295u})
std::printf("%10u: %s\n", n, is_prime(n) ? "prime" : "composite");
}primes below 10^6: 78498
561: composite
1105: composite
2147483647: prime
4294967291: prime
4294967295: composite
The count 78,498 agrees with the sieve; and are primes, the Carmichael numbers and are not. Practise with Prime Check and Sieve of Eratosthenes.
Test yourself
When Miller-Rabin answers "composite", how likely is it to be wrong?
- Never wrong
- At most
- At most
- At most
For and the sequence is . Why is 7 a witness?
- Because
- Because 67 is a square root of 1 modulo 561 that is neither 1 nor 560
- Because 241 is prime
- Because 561 is even
What error bound does Miller-Rabin achieve with independent random bases?
What is the bit cost of rounds of Miller-Rabin on a -bit number with schoolbook arithmetic?