TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Miller-Rabin: Error Bound and Cost

Miller-Rabin: Error Bound and Cost

Is a 1024-bit number prime? Trial division up to its square root would take about 25122^{512} 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 4−s4^{-s} after ss 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 an−1≡1(modn)a^{n-1} \equiv 1 \pmod n for a prime nn and every aa with 1≤a<n1 \le a < n. A base aa with an−1≢1a^{n-1} \not\equiv 1 is a proof that nn is composite. Unfortunately some composites, the Carmichael numbers (561=3⋅11⋅17561 = 3 \cdot 11 \cdot 17 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 11 and −1-1. Write n−1=2tun - 1 = 2^t u with uu odd and compute the sequence

x0=au mod n,x1=x02,…,xt=xt−12=an−1 mod n.x_0 = a^u \bmod n, \quad x_1 = x_0^2, \quad \ldots, \quad x_t = x_{t-1}^2 = a^{n-1} \bmod n .

If nn is prime, either x0=1x_0 = 1, or some xi=n−1x_i = n - 1 with i<ti < t (the last value before the sequence reaches 1 must be −1-1). If neither happens, aa is a witness: it proves nn composite, either through Fermat (xt≠1x_t \ne 1) or through a nontrivial square root of 1 (some xi≠±1x_{i} \ne \pm 1 with xi+1=1x_{i+1} = 1).

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

python · try it yourself
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 xx of 1 even reveals factors: nn divides (x−1)(x+1)(x - 1)(x + 1) but neither factor, so gcd⁡(x±1,n)\gcd(x \pm 1, n) are proper divisors.

How often is one round fooled?

A base aa that fails to be a witness for a composite nn is a strong liar. The key theorem:

Theorem (Monier, Rabin, 1980). For every odd composite n>9n > 9, at most φ(n)/4<n/4\varphi(n)/4 < n/4 of the bases 1≤a<n1 \le a < n 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 1/41/4, and ss independent rounds with probability below 4−s4^{-s}. The program counts the strong liars of some odd composites exactly, next to the Fermat liars.

python · try it yourself
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 1/41/4; the bound is nearly reached by numbers of the form (k+1)(2k+1)(k + 1)(2k + 1) with both factors prime, such as 703=19⋅37703 = 19 \cdot 37.

Cost

One round is one modular exponentiation with exponent u<nu < n plus at most t−1t - 1 squarings, together at most about 2β2\beta modular multiplications for a β\beta-bit nn, so O(β3)O(\beta^3) bit operations with schoolbook arithmetic (Modular Exponentiation and Its Bit Cost). With ss rounds:

T(β,s)=O(s β3),Pr⁡[error]≤4−s.T(\beta, s) = O(s\,\beta^3), \qquad \Pr[\text{error}] \le 4^{-s}.

Forty rounds push the error below 10−2410^{-24}. For random inputs the actual error is far smaller still, because most composites have very few strong liars. For bounded nn, fixed bases give a deterministic test: the bases 2,7,612, 7, 61 are correct for all n<4 759 123 141n < 4\,759\,123\,141, and the first twelve primes as bases for all nn below about 3.2⋅10233.2 \cdot 10^{23}. Since 2002 primality is also known to be in P deterministically (the AKS test), but Miller-Rabin remains the practical choice.

python · try it yourself
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.

cpp · try it yourself
#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; 231−12^{31} - 1 and 232−52^{32} - 5 are primes, the Carmichael numbers and 232−1=3⋅5⋅17⋅257⋅655372^{32} - 1 = 3 \cdot 5 \cdot 17 \cdot 257 \cdot 65537 are not. Practise with Prime Check and Sieve of Eratosthenes.

Test yourself

When Miller-Rabin answers "composite", how likely is it to be wrong?

  1. Never wrong
  2. At most 1/41/4
  3. At most 4−s4^{-s}
  4. At most 1/21/2

For n=561n = 561 and a=7a = 7 the sequence x0,…,x4x_0, \ldots, x_4 is 241,298,166,67,1241, 298, 166, 67, 1. Why is 7 a witness?

  1. Because x4≠1x_4 \ne 1
  2. Because 67 is a square root of 1 modulo 561 that is neither 1 nor 560
  3. Because 241 is prime
  4. Because 561 is even

What error bound does Miller-Rabin achieve with ss independent random bases?

  1. 2−s2^{-s}
  2. 4−s4^{-s}
  3. 1/s1/s
  4. s/ns/n

What is the bit cost of ss rounds of Miller-Rabin on a β\beta-bit number with schoolbook arithmetic?

  1. O(sβ)O(s\beta)
  2. O(sβ2)O(s\beta^2)
  3. O(sβ3)O(s\beta^3)
  4. O(2β/2)O(2^{\beta/2})