Algorithms · Visualized
Number Theory: Miller–Rabin
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Miller-Rabin is a probabilistic primality test that checks n against several 'witnesses' using modular exponentiation. Time: O(k log³ n) average, O(k log³ n) worst; space: O(log n).
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Miller-Rabin Primality Test
Number TheoryMiller-Rabin is a probabilistic primality test that checks n against several 'witnesses' using modular exponentiation. If n passes all rounds it is declared prime with extremely high confidence — much faster than trial division for the huge numbers used in cryptography.
How Miller–Rabin Works
- Write n − 1 as 2^s · d with d odd (factor out all powers of 2).
- Pick a base a in [2, n − 2] (e.g. 2, 3, 5, 7 for small n).
- Compute x = a^d mod n by fast modular exponentiation.
- If x equals 1 or n − 1, this witness says 'maybe prime' — try another.
- Otherwise square x up to s − 1 times; if it ever becomes n − 1, keep going; if it never does, n is definitely composite.
Miller–Rabin Worked Example
Input: {n: 561}
561 − 1 = 560 = 2^4 × 35, so s = 4, d = 35. Witness a = 2: x = 2^35 mod 561 = 263. Not 1 or 560, so square: 263² mod 561 = 166, then 67, then 1. The sequence reached 1 without ever hitting 560 → 561 is composite (it is 3 × 11 × 17, a Carmichael number).
def miller_rabin(n, bases=(2, 3, 5, 7)):
if n % 2 == 0:
return n == 2
d, s = n - 1, 0
while d % 2 == 0:
d //= 2
s += 1
for a in bases:
if a >= n - 1:
continue
x = pow(a, d, n)
if x in (1, n - 1):
continue
for _ in range(s - 1):
x = x * x % n
if x == n - 1:
break
else:
return False
return TrueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Miller–Rabin Time & Space Complexity
When to Use Miller–Rabin
- Generating large primes for RSA and cryptographic keys.
- Fast primality checks where deterministic trial division is far too slow.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.