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 is prime and (i.e., ), then:
For example, with and :
Fermat Primality Test
This gives a fast probabilistic primality test: if for some , then is definitely not prime. If , then 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 is prime:
This is because .
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 where for all coprime to . The smallest is 561 = 3 × 11 × 17. For reliable primality testing, use the Miller-Rabin test instead.
Your Task
Implement:
fermat_test(a, p)→Trueifmod_inverse_fermat(a, p)→ (modular inverse when 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.