Fermat Primality Test: Let n >1 be an integer. Choose a random integer a with 1 < a < n-1.
If a n-1≢ 1(mod n) then n is composite. If an-1 ≡ 1 (mod n), then n is probably prime.
If we are careful about how we do this successive squaring, the Fermat test can be combined with the basic principle to yield the following stronger result.
Miller- Rabin Primality test:
Let n >1 be an odd integer. Write a-1 =2km with m odd. Choose a random integer a with 1< a< n-1. Compute b0 ≡ am (mod n). If b0 ≡ ±1 (mod n), then stop and declare that n is probably prime. Otherwise, let b1 ≡ b02 (mod n). If b1 ≡ 1 (mod n), then n is composite (and gcd (b0 -1,n) gives a nontrivial factor of n ). If b1 ≡ -1 (mod n), then stop and declare that n is probably prime. Otherwise, let b2 ≡ b12 (mod n). If b2 ≡ 1 (mod n), then n is composite. If b2 ≡ -1 (mod n), then stop and declare that n is probably prime. Continue in this way until stopping and reaching bk-1. If bk-1≢ -1 (mod n), then n is composite.
The reason why the test works is- suppose, for example that b3≡1 (mod n). This means that b22≡1 (mod n). This means that b22≡12 (mod n). Apply the basic principle from before. Either b2≡±1 (mod n), or b2≢ ±1 (mod n) and n is composite. In the latter case, gcd (b2-1, n) give a nontrivial factor of n. In the former case, the algorithm would have stopped by the previous step.MILLER-RABIN (n, s)
- For j← 1 to s
- do a ← RANDOM(1,n-1)
- If WITNESS (a,n)
- then return COMPOSITE
- return PRIME
WITNESS (a, n)
- Let <bk,bk-1…b0 > be the binary representation of n-1.
- d←1
- for I ← k down to 0
- do x ← d
- d←(d. d) mod n
- if d=1 and x≠1 and x≠n-1
- then return TRUE
- if(bi=1) then
- d← (d. a) mod n
- end for
- if d≠1
- then return TRUE
- return FALSE