Primality: Miller-Rabin

17 Dec 2021


§ Motivation

The existence of Carmichael numbers makes it difficult to create a primality testing algorithm based on Fermat tests.

§ The Miller-Rabin Algorithm

The Miller-Rabin algorithm is a non-deterministic test for compositeness; i.e. if Miller-Rabin fails on a number nn then we say that nn is a probable prime. While non-deterministic, the probablity of failure is given by 4k4^{-k} where kk is the number of rounds of Miller-Rabin done, which means the failure probablity approaches zero very quickly.

There are Carmichael numbers that are strongly pseudoprime to a multitude of bases, but the occurrence of such numbers are extremely rare.

Let pp be an odd prime and let r=p1r = p - 1. Let k,qk, q be values that satisfy r=2kqr = 2^k \cdot q, and let aa be any integer not divisible by pp.

Then, one of the following conditions are true

  • aqp1a^q \equiv_p 1.
  • One of aq,a2q,a4q,,a2k1qa^q, a^{2q}, a^{4q}, \dots, a^{2^{k-1}q} is congruent to 1-1 modulo pp.

We know that ap11(modp)a^{p-1} \equiv 1 \pmod{p} by Fermat's. Hence, a2k1q±1a^{2^{k-1}q} \equiv \pm 1. If this value is 11, then a2k2qa^{2^{k-2}q} is also and so on. If a2lqp1a^{2^lq} \equiv_p 1 holds for all non-negative ll strictly less than kk, then the first statement holds. Otherwise, there must exist an ll such that the second statement holds.

Miller-Rabin Test

Suppose we want to factor an odd composite integer nn.

  1. Find k,qk, q with qq odd such that p1=2kqp - 1 = 2^k \cdot q.
  2. Choose a random integer aa.
  3. Compute aq(modp)a^q \pmod{p}. If aqp±1a^{q} \equiv_p \pm 1, stop. The test fails, nn is a probable prime to aa.
  4. Let aqa2q(modp)a^q \rightarrowtail a^{2q} \pmod{p}.
    • If the value is 11, stop. aa is a witness to the compositeness of nn.
    • If the value is 1-1, stop. nn is a probable prime to base aa.
  5. Repeat step 4 until a2kqqa^{2^{k-q}q}.
  6. If the test has not terminated by this point, then pp is composite.