Fermat's Little Theorem

The Setup

Pick any prime number pp.

Pick any number aa that’s not divisible by pp.


The Theorem

Raise aa to the power (p1)(p - 1). Divide by pp.

The remainder is always 1.

In notation:

ap1modp=1a^{p-1} \mod p = 1


Example

Let p=7p = 7 (prime) and a=3a = 3.

371=36=7293^{7-1} = 3^6 = 729

729÷7=104 remainder 1729 \div 7 = 104 \text{ remainder } 1

36mod7=13^6 \mod 7 = 1


Another Example

Let p=5p = 5 and a=2a = 2.

251=24=162^{5-1} = 2^4 = 16

16÷5=3 remainder 116 \div 5 = 3 \text{ remainder } 1

24mod5=12^4 \mod 5 = 1


Why It’s Useful

Imagine you need to compute 3100mod73^{100} \mod 7.

That’s a huge number. But we know 36mod7=13^6 \mod 7 = 1.


Rewrite the exponent:

100=6×16+4100 = 6 \times 16 + 4

So:

3100=36×16+4=(36)16×343^{100} = 3^{6 \times 16 + 4} = (3^6)^{16} \times 3^4

Since 36mod7=13^6 \mod 7 = 1:

=116×34=81= 1^{16} \times 3^4 = 81

81mod7=481 \mod 7 = 4

Instead of computing 31003^{100}, we only needed 343^4.