Fermat's Little Theorem
Raise any number to the power modulo a prime and you get 1. This one fact gives fast modular inverses, the first primality tests, Pollard's factoring method and, generalized by Euler, the correctness of RSA.
Statement
If is prime and , then
Equivalently, for every integer (this form also covers ).
p = 13
print([pow(a, p - 1, p) for a in range(1, p)])
print([pow(a, p, p) == a % p for a in range(-3, 20)].count(False))
print("composite 15:", [pow(a, 14, 15) for a in range(1, 15)])[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
0
composite 15: [1, 4, 9, 1, 10, 6, 4, 4, 6, 10, 1, 9, 4, 1]
For the composite 15 the pattern breaks: most bases do not give 1. That is the idea of the Fermat primality test.
Proof by rearrangement
Multiply each of by modulo . The results are again in a different order: none is 0 (as , ) and no two coincide (if then , since is invertible). So the products agree:
is invertible modulo , so cancel it: .
p, a = 11, 7
print(sorted(a * k % p for k in range(1, p))) # a permutation of 1..10[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Proof by counting necklaces
A second proof shows why is divisible by : there are strings of length over an alphabet of letters. Remove the constant strings. The remaining fall into groups of exactly rotations each (because is prime, no non-constant string equals a nontrivial rotation of itself). So .
Uses
Reducing exponents. Modulo a prime , exponents can be reduced modulo : when . Example: . Since and , it equals .
Inverses. (Modular Inverses).
Wilson's theorem, a cousin: is prime iff . It is a correct but useless primality test, since computing the factorial takes steps.
from math import factorial
print(pow(3, 1000, 7), pow(3, 1000 % 6, 7))
print([(n, factorial(n - 1) % n) for n in range(2, 14)])4 4
[(2, 1), (3, 2), (4, 2), (5, 4), (6, 0), (7, 6), (8, 0), (9, 0), (10, 0), (11, 10), (12, 0), (13, 12)]
In software
- Elliptic-curve libraries invert field elements as because the exponent is public and fixed, so the computation is naturally constant-time.
- Fermat's theorem underlies the fast probable-prime checks that every key generator runs (Miller-Rabin).
Exercises
Exercise 1: Reduce the exponent
Compute by hand.
Answer
Solution
and , so .
Exercise 2: A divisibility fact
Show that is divisible by 7 for every integer , and also by 42.
Answer
Fermat for , 3 and 2.
Solution
is Fermat. Also ; modulo 3, gives ; modulo 2, since parity is preserved. So 2, 3 and 7 all divide it, hence 42.
Exercise 3: Check numerically (code)
Verify for from to , and find the largest dividing for all those .
Answer
.
Solution
from math import gcd
from functools import reduce
vals = [n**7 - n for n in range(-100, 101)]
print(all(v % 42 == 0 for v in vals), reduce(gcd, vals))True 42
Test yourself
For a prime not dividing , Fermat's little theorem gives…
Modulo the prime 11, equals (for )…
In the rearrangement proof, multiplying by modulo …
- gives all zeros
- permutes them
- doubles them
- sorts them