Fermat's Little Theorem
- •
What it is
- •
For a prime and any integer not divisible by , . A direct corollary gives a fast way to compute modular inverses under a prime modulus without the extended Euclidean algorithm.
- •
- •
When to apply
- •
The modulus is prime and you need either to verify/exploit an exponentiation identity, or to invert an element mod p quickly with a single
pow()call.
- •
- •
Symbols and assumptions
- •
is prime and . A congruence means equal remainders, not equality as ordinary integers.
- •
- •
Math — step by step
- •
- Multiply the nonzero residues by . They remain nonzero and distinct: implies , because is invertible modulo the prime.
- •
- The multiplication merely permutes the set. Therefore . The factorial is nonzero modulo , so cancel it to obtain .
- •
- Write . This identifies as the inverse. Do not apply this inverse formula to zero or to an arbitrary composite modulus.
- •
- •
- •
Python
- •
inverse = pow(a, p - 2, p)
- •
- •
SageMath
- •
inverse = power_mod(3, -1, 13) # 9, Sage resolves negative exponents directly inverse = inverse_mod(3, 13) # 9, equivalent dedicated function
- •
- •
- •
Linked references 9
- cryptohack
- Diffie-Hellman (Textbook Construction)
- ElGamal (Subgroup and Quadratic-Residue Leakage)
- Extended Euclidean Algorithm
- Groups (Group Theory Basics)
- RSA (Textbook Construction)
- RSA Factorization from Known (N, e, d)
- RSA Fixed-Point Leakage (Unconcealed Messages) → Factorization
- RSA with Non-Coprime Exponent (e Shares a Factor with φ(N))