TExcelTAD
Home › Number Theory & Cryptography › The Fermat Primality Test

The Fermat Primality Test

Trial division cannot test a 300-digit number. Fermat's little theorem gives a test that runs in milliseconds: if an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod{n}, then nn is certainly composite. If the congruence holds for several bases, nn is probably prime.

The test

By Fermat's Little Theorem, a prime nn satisfies an−1≡1(modn)a^{n-1} \equiv 1 \pmod n for all aa coprime to nn. Read contrapositively:

  • If an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod{n} for some aa with 1<a<n−11 < a < n - 1, then nn is composite, and aa is a Fermat witness. We learn nn is composite without finding a factor.
  • If an−1≡1a^{n-1} \equiv 1, then nn is a probable prime to base aa. A composite that passes is a Fermat pseudoprime to base aa, and aa is a Fermat liar.
python · try it yourself
def fermat_test(n, bases=(2, 3, 5, 7)):
    for a in bases:
        if a % n and pow(a, n - 1, n) != 1:
            return False, a          # a is a witness: n is composite
    return True, None

for n in (561, 1001, 1_000_003, 2**61 - 1, 2**61 + 1, 2**89 - 1):
    print(n, fermat_test(n))
561 (False, 3)
1001 (False, 2)
1000003 (True, None)
2305843009213693951 (True, None)
2305843009213693953 (False, 2)
618970019642690137449562111 (True, None)

The 1001 case shows a witness found immediately. 561 fools every base listed except bases sharing a factor with it, a Carmichael number (next lesson).

How often does it lie?

For base 2, pseudoprimes exist but are rare: the smallest is 341=11⋅31341 = 11 \cdot 31.

python · try it yourself
from sympy import isprime

psp2 = [n for n in range(3, 100000, 2) if not isprime(n) and pow(2, n - 1, n) == 1]
print(len(psp2), psp2[:10])
both = [n for n in psp2 if pow(3, n - 1, n) == 1]
print("also pass base 3:", len(both), both[:8])
78 [341, 561, 645, 1105, 1387, 1729, 1905, 2047, 2465, 2701]
also pass base 3: 23 [1105, 1729, 2465, 2701, 2821, 6601, 8911, 10585]

Below 100000 there are 78 base-2 pseudoprimes, against 9592 primes, and most fail base 3 as well.

Liars are at most half (usually)

For a composite nn, the Fermat liars form a subgroup of the units. If there is even one witness coprime to nn, the subgroup is proper, so at most half the units are liars. Then kk random bases miss with probability at most 2−k2^{-k}.

python · try it yourself
from math import gcd

def liar_fraction(n):
    units = [a for a in range(1, n) if gcd(a, n) == 1]
    liars = [a for a in units if pow(a, n - 1, n) == 1]
    return len(liars), len(units)

for n in (341, 91, 1001, 561):
    l, u = liar_fraction(n)
    print(f"n={n:5}  liars {l:4} of {u:4} units  ({l / u:.1%})")
n=  341  liars  100 of  300 units  (33.3%)
n=   91  liars   36 of   72 units  (50.0%)
n= 1001  liars   80 of  720 units  (11.1%)
n=  561  liars  320 of  320 units  (100.0%)

The exception is 561: every unit is a liar. Numbers like that break the "at most half" argument, which is why practical code uses Miller-Rabin instead.

In software

  • PGP and some older libraries used Fermat tests with a few small bases to generate keys; they were acceptable because random large numbers are very unlikely to be Carmichael numbers.
  • The test is still used as a cheap pre-filter. GMP's mpz_probab_prime_p runs trial division, then a base-210 Fermat-style check, then Miller-Rabin rounds.

Exercises

Exercise 1: A witness by hand

Show that 2 is a Fermat witness for n=15n = 15.

Answer

214≡4(mod15)2^{14} \equiv 4 \pmod{15}.

Solution

24=16≡1(mod15)2^4 = 16 \equiv 1 \pmod{15}, so 214=212⋅22≡1⋅4=4≠12^{14} = 2^{12} \cdot 2^2 \equiv 1 \cdot 4 = 4 \ne 1. Hence 15 is composite, which we knew, but the test did not need a factor.

Exercise 2: 341

Verify that 2340≡1(mod341)2^{340} \equiv 1 \pmod{341} although 341=11⋅31341 = 11 \cdot 31.

Answer

210=1024=3⋅341+1≡12^{10} = 1024 = 3 \cdot 341 + 1 \equiv 1, and 340=10⋅34340 = 10 \cdot 34.

Solution

Since 210≡1(mod341)2^{10} \equiv 1 \pmod{341}, 2340=(210)34≡12^{340} = (2^{10})^{34} \equiv 1. Base 3 exposes it: 3340≡56(mod341)3^{340} \equiv 56 \pmod{341} (check with pow(3, 340, 341)).

Exercise 3: First pseudoprimes (code)

Find the smallest odd Fermat pseudoprime to base 3 and to base 5.

Answer

91 for base 3 and 217 for base 5.

Solution
python · try it yourself
from sympy import isprime
for a in (3, 5):
    print(a, next(n for n in range(3, 10**6, 2) if not isprime(n) and pow(a, n - 1, n) == 1))
3 91
5 217

91=7⋅1391 = 7 \cdot 13 and 217=7⋅31217 = 7 \cdot 31. Each base has its own pseudoprimes, so combining bases helps, except against Carmichael numbers.

Test yourself

If an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod{n}, then…

  1. nn is prime
  2. nn is composite
  3. aa is prime
  4. nothing can be concluded

The smallest base-2 Fermat pseudoprime is…

  1. 91
  2. 341
  3. 561
  4. 1105

Why can a Fermat test with many bases still fail?

  1. exponentiation is inexact
  2. Carmichael numbers pass for every base coprime to them
  3. large primes fail it
  4. it needs factoring