Fermat's Little Theorem

lean4-proofnumber-theorymodular-arithmeticvisualization
apa(modp)a^p \equiv a \pmod{p}

Statement

If pp is a prime number, then for any integer aa:

apa(modp)a^p \equiv a \pmod{p}

Equivalently, if gcd(a,p)=1\gcd(a, p) = 1:

ap11(modp)a^{p-1} \equiv 1 \pmod{p}

Proof via Necklace Counting

Consider the set of all strings of length pp over an alphabet of aa symbols. There are apa^p such strings total. Exactly aa of them are constant (all symbols the same). The remaining apaa^p - a strings can be grouped into equivalence classes under cyclic rotation, each of size exactly pp (since pp is primeInfinitude of PrimesnN,  p>n  such that  p  is prime\forall\, n \in \mathbb{N},\; \exists\, p > n \;\text{such that}\; p \;\text{is prime}Euclid's classic proof that there are infinitely many prime numbersRead more → and the string is non-constant). Therefore p(apa)p \mid (a^p - a), giving us apa(modp)a^p \equiv a \pmod{p}.

Applications

  • Primality testing: Fermat's test checks whether an11(modn)a^{n-1} \equiv 1 \pmod{n}
  • RSA cryptography: The RSA algorithm relies on Euler's generalization of this theorem
  • Modular inverses: When gcd(a,p)=1\gcd(a, p) = 1, the inverse of aa modulo pp is ap2a^{p-2}

Connections

This theorem builds on the Fundamental Theorem of ArithmeticFundamental Theorem of Arithmeticn=p1a1p2a2pkakn = p_1^{a_1} \cdot p_2^{a_2} \cdots p_k^{a_k}Every integer greater than 1 has a unique prime factorizationRead more → and is a key ingredient in Quadratic ReciprocityQuadratic Reciprocity(pq)(qp)=(1)p12q12\left(\frac{p}{q}\right)\left(\frac{q}{p}\right) = (-1)^{\frac{p-1}{2}\cdot\frac{q-1}{2}}Relationship between solvability of quadratic congruences for two odd primesRead more →.

Lean4 Proof

/-- Fermat's little theorem: in `ZMod p`, every element raised to the
    p-th power is itself. Mathlib bundles the necklace-counting argument
    (and the polynomial-identity argument) into `ZMod.pow_card`. -/
theorem fermat_little (p : ) [Fact p.Prime] (a : ZMod p) : a ^ p = a :=
  ZMod.pow_card a

/-- Equivalent form for nonzero residues: `a^(p-1) = 1`. -/
theorem fermat_little_nonzero (p : ) [Fact p.Prime] {a : ZMod p}
    (ha : a  0) : a ^ (p - 1) = 1 :=
  ZMod.pow_card_sub_one_eq_one ha