Maths WorkshopMaths problems with full solutions
Exercise 2123Number theory › Divisibility and gcdM1Added 3 Nov 2026

The Miller–Rabin test

#primality testing#Miller-Rabin#modular arithmetic

Statement

Describe the Miller–Rabin primality test for odd n>2n>2, writing n−1=2s⋅dn-1=2^s\cdot d with dd odd.

Hint

For a base aa, compute ad mod na^d\bmod n, then square repeatedly up to ss times.

Show solutionHide solution

Solution

Setup. Write n−1=2s⋅dn-1=2^s\cdot d with dd odd. Choose a base aa with 1<a<n−11<a<n-1.

Test. Compute x=ad mod nx=a^d\bmod n. Then square ss times:
- if x≡1x\equiv1 or x≡n−1x\equiv n-1, the base is a witness for primality;
- otherwise, if after squaring ss times we reach neither 11 nor n−1n-1, the base is a witness for compositeness.

Correctness. If nn is prime, Fermat's little theorem plus the structure of Z/nZ∗\mathbb{Z}/n\mathbb{Z}^* ensures every coprime base is a witness for primality. If nn is composite, at least 3/43/4 of bases are witnesses for compositeness (for odd composite nn).

Conclusion. Miller–Rabin is a probabilistic test with error probability ≤(1/4)k\le(1/4)^k for kk bases.