Lesson 14 of 15

Fermat's Little Theorem

Fermat's Little Theorem

Fermat's Little Theorem (proved by Fermat in 1640, published by Euler in 1736) states:

If pp is prime and gcd(a,p)=1\gcd(a, p) = 1 (i.e., pap \nmid a), then: ap11(modp)a^{p-1} \equiv 1 \pmod{p}

For example, with a=2a = 2 and p=7p = 7: 26=64=97+11(mod7)2^6 = 64 = 9 \cdot 7 + 1 \equiv 1 \pmod{7}

Fermat Primality Test

This gives a fast probabilistic primality test: if ap1≢1(modp)a^{p-1} \not\equiv 1 \pmod{p} for some aa, then pp is definitely not prime. If ap11(modp)a^{p-1} \equiv 1 \pmod{p}, then pp is probably prime (but may be a Carmichael number).

def fermat_test(a, p):
    return pow(a, p - 1, p) == 1

print(fermat_test(2, 7))   # True  (7 is prime)
print(fermat_test(2, 11))  # True  (11 is prime)

Modular Inverse via Fermat

Fermat's theorem gives us a way to compute modular inverses when pp is prime:

a1ap2(modp)a^{-1} \equiv a^{p-2} \pmod{p}

This is because aap2=ap11(modp)a \cdot a^{p-2} = a^{p-1} \equiv 1 \pmod{p}.

def mod_inverse_fermat(a, p):
    return pow(a, p - 2, p)

# 3^(-1) mod 7: 3 * ? ≡ 1 (mod 7)
print(mod_inverse_fermat(3, 7))   # 5  (since 3*5=15≡1 mod 7)

When Fermat's Test Fails

Carmichael numbers are composite numbers nn where an11(modn)a^{n-1} \equiv 1 \pmod{n} for all aa coprime to nn. The smallest is 561 = 3 × 11 × 17. For reliable primality testing, use the Miller-Rabin test instead.

Your Task

Implement:

  • fermat_test(a, p)True if ap11(modp)a^{p-1} \equiv 1 \pmod{p}
  • mod_inverse_fermat(a, p)ap2modpa^{p-2} \bmod p (modular inverse when pp is prime)

You may use Python's built-in pow(a, exp, mod) for these.

Python runtime loading...
Loading...
Click "Run" to execute your code.