Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Number Theory

Probably Prime.

Watch the explainer

Factoring a 300-digit number is infeasible — yet cryptography needs to generate huge primes constantly. Miller–Rabin tests primality without factoring. Write n−1 = 2ˢ·d, pick a base a, and check whether the chain aᵈ, a²ᵈ, a⁴ᵈ, … (mod n) behaves the way it must for a prime. If it doesn’t, a is a witness that proves n composite — with certainty. If it does, n is probably prime, and each extra base you try cuts the error to at most 4⁻ᵏ. Test bases and watch composites get caught.

O(k · log³ n) · one witness = certainly composite · k passes = prime, error ≤ 4⁻ᵏ
n − 1 = 2ˢ·d

Factor out all the twos: d is odd, s counts the twos removed.

base a

A number tested as a potential witness against n’s primality.

witness

A base whose square-chain misbehaves — it proves n is composite, no doubt.

probably prime

Passing k bases leaves error ≤ 4⁻ᵏ — vanishing fast with more bases.

miller-rabin.js — witnesses and pseudoprimes
Ready
Testing a number for primality. We factor n−1 = 2ˢ·d, then try bases one at a time. A base whose modular-square chain misbehaves is a witness proving n composite. Test base to begin.
0
bases tried
?
verdict
–
max error

How it works

The test rests on a fact about primes: modulo a prime, the only square roots of 1 are +1 and −1. For a prime n, the chain aᵈ, a²ᵈ, …, a²ˢ⁻¹ᵈ must therefore either start at 1, or hit n−1 somewhere before the end (so that squaring it gives 1 legitimately). If a base produces a chain that reaches 1 having not passed through n−1 — a “nontrivial square root of 1” — then n cannot be prime, and that base is a witness. The deep guarantee is that at least three-quarters of all bases are witnesses for any composite, so each random base you pass shrinks the error by a factor of four.

1

Factor out the twos

Write n − 1 = 2ˢ · d with d odd. This exposes the chain of s squarings the test will inspect.

2

Compute the base’s chain

For base a, compute aᵈ mod n, then keep squaring: a²ᵈ, a⁴ᵈ, …, up to s−1 squarings.

3

Check the chain

It passes if the first value is 1, or if any value in the chain equals n−1. Otherwise the base is a witness — n is composite, with certainty.

✓

Repeat to shrink the error

One witness proves composite for good. If a base passes, try more: at least ¾ of bases witness any composite, so after k passing bases the chance n is actually composite is at most 4⁻ᵏ.

Time
O(k · log³ n)
One witness
certainly composite
k passes
error ≤ 4⁻ᵏ
Used in
RSA key-gen

The code

# one Miller-Rabin round for odd n > 2 and base a def is_probable_prime(n, a): d, s = n - 1, 0 while d % 2 == 0: d //= 2; s += 1 # n-1 = 2^s * d x = pow(a, d, n) # a^d mod n if x == 1 or x == n - 1: return True # passes this base for _ in range(s - 1): x = x * x % n # square up the chain if x == n - 1: return True # reached -1: ok return False # a is a WITNESS -> composite

Quick check

1. What does it mean when a base is a "witness" in Miller–Rabin?

2. What does passing k random bases tell you?

3. Why does Miller–Rabin beat the Fermat primality test?

FAQ

What is the Miller–Rabin primality test?

A probabilistic algorithm that tests primality without factoring. It writes n − 1 = 2ˢ·d, then for a base a checks whether the chain aᵈ, a²ᵈ, … mod n behaves as it must for a prime. If not, a is a witness proving n composite for certain; if it passes, n is probably prime, with error ≤ 4⁻ᵏ after k bases.

Is Miller–Rabin ever wrong?

It never calls a prime composite — a witness is a proof. It can, with probability ≤ 4⁻ᵏ, call a composite "probably prime" if every base is a non-witness, but that shrinks fast. For numbers below known bounds, testing a fixed base set makes it fully deterministic.

What is a Carmichael number and why does it matter here?

A composite that passes the Fermat test for every coprime base, making Fermat unreliable. Miller–Rabin’s stronger square-root condition exposes them — every suitable base witnesses a Carmichael number — which is a main reason it’s preferred over Fermat.

Where is Miller–Rabin used?

Prime generation in cryptography — RSA, Diffie–Hellman, and DSA all need large random primes, and Miller–Rabin tests candidates fast. Libraries run several rounds so the error is negligible, sometimes with a deterministic follow-up.

The picture: two chains of squares

561base 297base 22631666712³⁵squared67² ≡ 1: a false root1 reached, 560 never seen: base 2 is a witness, 561 is composite8642296196 = n − 1 appears: base 2 passes, 97 is probably prime
Each box is the previous box squared modulo n. The top chain, for 561, goes 263, 166, 67, 1: it lands on 1 without ever visiting 560, which is impossible for a prime. The bottom chain, for 97, passes through 96 (that is, −1) and is allowed to continue to 1 after it.

Worked example, step by step

The page’s test targets are 561 and 1105, two Carmichael numbers. Take 561 first with bases 2 and 5, then a prime (97) for contrast, then 2047, which fools base 2 but not base 3. Every value below was computed with exact integer arithmetic.

n / baseStepValueVerdict
5611n − 1 = 560 = 2⁴ · 35, so s = 4, d = 35—
561 / base 222³⁵ mod 561 = 263not 1, not 560
561 / base 23263² mod 561 = 166not 560
561 / base 24166² mod 561 = 67not 560
561 / base 2567² mod 561 = 11 without passing 560: witness
561 / base 52–523, 529, 463, 67never 560: witness again
971n − 1 = 96 = 2⁵ · 3, so s = 5, d = 3—
97 / base 222³ mod 97 = 8not 1, not 96
97 / base 23–48² = 64, 64² = 4096 mod 97 = 22not 96
97 / base 2522² mod 97 = 96= n − 1: pass
2047 / base 2alln − 1 = 2046 = 2¹ · 1023; 2¹⁰²³ mod 2047 = 1starts at 1: pass (a strong liar)
2047 / base 3all3¹⁰²³ mod 2047 = 1565not 1, not 2046: witness

The 561 chain ends ...67, 1. Since 67² ≡ 1 (mod 561) while 67 is neither 1 nor 560, 67 is a square root of 1 that a prime modulus cannot have. That is the proof of compositeness, and it is exactly what the plain Fermat test cannot see: 561 satisfies a⁵⁶⁰ ≡ 1 for all 318 bases in 2..559 that share no factor with it. The strong test is far stricter. Of the 558 bases 2..559, only 8 pass for 561, and for 1105 only 28 of 1102 do. Both are well under the one-quarter ceiling. The last two rows show why one base is not enough: 2047 is composite and passes base 2, so you need more than one.

Complexity and trade-offs

CaseTimeSpaceWhy
Miller-Rabin, k basesO(k · log³ n) with schoolbook multiplicationO(log n)Each base costs one modular exponentiation plus at most s − 1 extra squarings. For 2⁶¹ − 1 (where s = 1) the full 12-base test took 1440 modular multiplications when counted.
Trial divisionO(√n)O(1)For 2⁶¹ − 1, √n is about 1.5 billion divisors to try. Exact and simple, hopeless past roughly 10¹⁵.
Fermat testO(k · log³ n)O(log n)Same cost as Miller-Rabin but wrong for Carmichael numbers: 561 passes every coprime base.
Sieve of EratosthenesO(n log log n)O(n)Right when you need every prime up to n, wrong for testing a single huge number.
AKSpolynomial in log npolynomial in log nDeterministic and proven, but its polynomial is of high degree, so Miller-Rabin is what practical code uses.

The trade is certainty for speed: a “composite” answer is a proof, a “prime” answer is a bound. With fixed small bases the bound disappears for bounded inputs. Bases 2 and 3 alone give the right answer for every n below 1,373,653 (checked exhaustively), and 1,373,653 itself is a composite that passes both. For 64-bit inputs the standard practice is a fixed list of bases known to be sufficient, and for larger numbers random bases and a rounds count.

Common mistakes

  • Checking only for n − 1

    Skipping the “first value is 1” case rejects primes. Testing 7 with base 2 gives 2³ mod 7 = 1 and the chain never contains 6, so code that looks only for n − 1 calls the prime 7 composite. It is correct to pass when the very first value is 1.

  • Multiplying in a fixed-width integer

    The product of two residues below n is up to n², so a 64-bit n overflows 64-bit arithmetic. In JavaScript, doing the multiply with Number loses bits past 2⁵³. Running the 12-base test on the prime 2⁶¹ − 1 with a Number multiply returned false; with exact arithmetic it returned true. Use a wide multiply, BigInt, or a mulmod routine.

  • Trusting a single base

    Base 2 alone calls 2047 prime, and also 3277, 4033 and 4681. Always use several bases, or a fixed list proven sufficient for your input range.

  • Using the Fermat test as a shortcut

    pow(a, n-1, n) == 1 is true for 561 for each of 318 coprime bases, so no number of rounds will expose it. The strong version’s extra square-root check is the point of the algorithm.

  • Letting the base be a multiple of n

    With a = n, aᵈ mod n is 0, and the test calls a prime like 7 composite. Reduce bases with a % n and skip any that reduce to 0, or handle small n separately before testing.

Where this shows up

  • Prime generation for cryptography

    RSA and Diffie-Hellman need random primes hundreds of digits long. The usual recipe is to draw a random odd number, throw out small factors by trial division, then run a few Miller-Rabin rounds.

  • Deterministic 64-bit checks

    Programming-contest and systems libraries fix a small list of bases that is known to be correct for every 64-bit integer, so the answer is exact and still takes only a few modular exponentiations.

  • Factoring helpers

    Pollard’s rho and other factoring methods call a primality test to decide when a factor is finished, so they need one that is both fast and reliable on large inputs.

  • Hash tables and random choices

    Picking a prime modulus for a hash table or a field for a protocol is a one-time cost where a quick probabilistic test is plenty.

SOLVE IT YOURSELF

Solve it: primality testing that Carmichael numbers cannot fool

Fermat’s little theorem gives a cheap primality test — and 561 defeats it completely. Miller–Rabin patches the hole by looking at the square roots on the way. Runs for real in your browser.

YOUR TASK

Implement is_prime(n) using the Miller–Rabin witness test with a fixed set of bases. Your test must correctly reject 561 and 1105 — Carmichael numbers, which pass the naive Fermat test for every base coprime to them.

HINTS — 6 IDEAS
  1. Handle the small cases first: n < 2 is not prime, and trial-divide by the small primes so the main loop never sees them.
  2. Write n − 1 = d · 2ʳ with d odd — keep halving n − 1 and counting.
  3. For each base a, compute x = aᵈ mod n. If x is 1 or n − 1, this base is satisfied.
  4. Otherwise square x up to r − 1 times, looking for n − 1. Find it and the base is satisfied; never find it and n is definitely composite.
  5. The insight Fermat misses: modulo a prime, the only square roots of 1 are ±1. A composite can have others, and spotting one is a proof of compositeness — which is exactly what catches Carmichael numbers.
  6. With the bases 2, 3, 5 … 37 the test is deterministic for every n below 3.3·10²⁴, not merely probabilistic.
CPython · WebAssembly

Keep going

▶  Watch it explained

Miller-Rabin: Is This 18-Digit Number Prime? 10.7 Microseconds

Finished this one? 0 / 99 Algorithms done
NextPollard's Rho: Factor by Collision Next on the “Number theory, in order” ladder · rung 6 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms