Skip to content
StackDecode
Number theory & mathAnimated

Fermat's Little Theorem

a^(p−1) ≡ 1 (mod p) for prime p, so a⁻¹ = a^(p−2).

Time

O(log p)

Extra space

O(1)

Use it for

Modular inverse mod a prime.

How it works

  1. Fermat’s little theorem: if p is prime and p does not divide a, then a^(p−1) ≡ 1 (mod p).
  2. Divide both sides by a: a · a^(p−2) ≡ 1 (mod p). So the modular inverse of a is a^(p−2) mod p.
  3. Compute it quickly with repeated squaring.
  4. Check: multiply a by the inverse; the result must be 1 mod p.

Watch it run

Loading animation…