Fermat's Little Theorem in Puzzles
Fermat's little theorem says that for a prime p, any number raised to the p-1 power leaves remainder 1 when divided by p (unless it's a multiple of p) — a one-line fact that collapses huge modular-power interview questions into small arithmetic.
Prerequisites: Finding the Last Digit of a Huge Power
What is the remainder when is divided by 101? Computing directly gives a 31-digit number — not something to do by hand in an interview. But 101 is prime, and that single fact makes the problem almost trivial once you know Fermat's little theorem.
The core idea: a prime modulus forces powers to cycle back to 1
Fermat's little theorem states: if is a prime number and is any integer not divisible by , then
In plain English: raise to the power one less than the prime, divide by the prime, and the remainder is always exactly 1 — no matter which valid or which prime you pick. This holds because the nonzero remainders under multiplication modulo form a tightly structured group (every nonzero remainder has a multiplicative "partner" that undoes it), and a foundational fact about that structure — closely related to counting how repeated multiplication permutes the remainders — forces every element's -th power back to 1.
Worked example 1:
Since 101 is prime and isn't a multiple of 101, Fermat's little theorem gives directly — the exponent 100 is exactly for , so no further computation is needed. The remainder is 1.
Worked example 2: an exponent that isn't exactly
What is ? Here is prime, so Fermat's little theorem says . The exponent 206 isn't , but you can use the theorem to reduce it: since , any multiple of 6 in the exponent also gives 1, so . And . So . The technique generalizes: to compute for prime , first reduce the exponent modulo (using Fermat's little theorem to collapse full cycles of down to 1), then compute the much smaller resulting power directly.
For a prime and not divisible by : . To compute for a large , reduce the exponent modulo first, then compute the small remaining power — never compute the huge power directly.
What this means in practice
This is the number-theoretic engine behind RSA encryption and most public-key cryptography, where huge modular exponentiations need to be both computable and provably hard to reverse without the right key. In interviews, the pattern-recognition step — noticing that a modulus is prime and that the question is really asking for a modular power — is the real skill being tested, since the theorem itself is a one-line lookup once you spot it applies.
Fermat's little theorem requires to be prime and to not be a multiple of . Applying it when the modulus is composite (not prime) gives wrong answers — that case needs the more general Euler's theorem, which replaces with Euler's totient function counting numbers coprime to .
Related concepts
Practice in interviews
Further reading
- Niven, Zuckerman & Montgomery, An Introduction to the Theory of Numbers, ch. 2