Miller-Rabin Primality Test
Decompose n-1 into an odd part and powers of two, then test modular witnesses for compositeness.
Core idea
For odd n, write n minus one as d times a power of two. A prime must make each witness produce one immediately or reach minus one while repeatedly squaring.
Read the visualization
The decomposition fixes d and the squaring count. Each witness row begins with modular exponentiation, then follows residues until it passes or proves n composite.
| a^d | square ¹ | square ² | square ³ | |
|---|---|---|---|---|
| 41( true prime) | ||||
| 561( probable prime) |
Choose the next witness base for this odd primality candidate.
Complexity and tradeoffs
Time: O(k log^3 n). Space: O(1). A fixed witness set is deterministic for bounded machine integers; random witnesses give tiny error probability.
Where it fits
Miller-Rabin is the standard fast primality screen for cryptography and factorization. Fixed witness sets make it deterministic over common 64-bit ranges.