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
- Fermat’s little theorem: if p is prime and p does not divide a, then a^(p−1) ≡ 1 (mod p).
- Divide both sides by a: a · a^(p−2) ≡ 1 (mod p). So the modular inverse of a is a^(p−2) mod p.
- Compute it quickly with repeated squaring.
- Check: multiply a by the inverse; the result must be 1 mod p.
Watch it run
Loading animation…