Fermat’s little theorem
Raise a number to the power p − 1 on a ring of prime size p and it always comes back to 1. We watch it happen, see why, then use it to test for primes and to explain RSA.
In 30 seconds
Fermat’s little theorem is a fact about remainders. If p is prime and a is not a multiple of p, then the product of p − 1 copies of a leaves remainder 1 when divided by p.
For example, 3 to the 6th power is 729, which is 104 × 7 + 1.
This gives a shortcut for huge powers, and a quick test: if a number n fails the pattern, n is certainly not prime. The same fact is the reason RSA decryption returns the original message.
Fermat’s little theorem, step by step
The RSA step assumes m shares no factor with n; RSA still works for every m, by a slightly longer argument. Combining the two primes uses the fact that they have no common factor.
- Step 1: Powers on a ring. Work mod 7, keeping only remainders. Start at 1 and keep multiplying by 3: the results hop round the ring through 3, 2, 6, 4, 5 and, on the sixth step, return to 1. Fermat’s little theorem says that this return is no accident.
- Step 2: The theorem. Try every base from 1 to 6. The rows differ, yet the column for exponent 6 holds only 1s. That is the theorem: if p is prime and a is not a multiple of p, then a raised to the power p − 1 leaves remainder 1 when divided by p.
- Step 3: Why it works. Multiply each of 1 to 6 by 3 mod 7 and you get the same six numbers shuffled; no two collide because 3 has an inverse mod 7. So both rows have the same product: 3 to the 6th times 720 is congruent to 720. Because 7 is prime, 720 can be cancelled, leaving 1.
- Step 4: A worked example. What is the remainder of 2 to the power 103 divided by 11? Since 11 is prime, 2 to the 10th is 1 mod 11, so every block of ten in the exponent contributes a factor of 1. Only the 3 left over matters, and 2 cubed is 8.
- Step 5: A test for primes. Turn the theorem round. If n is prime, 2 to the power n − 1 must leave remainder 1. For 91 it leaves 64, so 91 cannot be prime, and we learn that without finding a factor. 97 gives 1, which is consistent with being prime but does not prove it.
- Step 6: Composites that pass. Some composite numbers slip through. 341 is 11 × 31, yet base 2 gives 1. Trying base 3 exposes it. A few rare numbers, the Carmichael numbers such as 561, fool every base that shares no factor with them, so real software uses a stricter relative of this test, Miller–Rabin.
- Step 7: Inside RSA. RSA encrypts by raising m to the power e and decrypts by raising to d, both mod n = 61 × 53. The exponents multiply to 15 × 3120 + 1, and 3120 is a multiple of both 60 and 52. By Fermat, m to the 3120 is 1 mod 61 and mod 53, hence mod n, and exactly one m is left.
Try it yourself
Learn this first
Spotted a mistake on this page?