Sub topic 3
Fermat's Little Theorem
This chapter assumes you know integer division with quotient and remainder, prime numbers and prime factorisation, and exponent rules. The division algorithm says that n = d × q + r, where 0 ≤ r < d. We write this as n ≡ r (mod d), read "n is congruent to r modulo d."
Fermat's Little Theorem
If p is prime and p does not divide a, then a^(p-1) ≡ 1 (mod p). Use it to shrink a large exponent by reducing it modulo p − 1.
For 2^100 mod 13, note that 100 mod 12 = 4. So 2^100 ≡ 2^4 = 16 ≡ 3 (mod 13).
Euler's Totient and Euler's Theorem
Euler's totient, φ(n), counts the integers from 1 to n that share no factor with n. For example, φ(10) = 4, because 1, 3, 7 and 9 qualify.
Euler's theorem extends Fermat's theorem to any modulus. If gcd(a, n) = 1, then a^φ(n) ≡ 1 (mod n). Since φ(10) = 4, we get 7^100 ≡ 1 (mod 10).
Wilson's Theorem and Factorials
For a prime p, (p − 1)! ≡ −1 (mod p). So 100! ≡ 100 (mod 101).
If n ≥ p, then n! contains the factor p, so n! ≡ 0 (mod p). For a sum of factorials, reduce each term separately and then add the remainders.
Combining Remainder Conditions
When a number leaves specified remainders on pairwise coprime divisors, the Chinese Remainder Theorem guarantees exactly one solution modulo their product. For x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7), the unique solution below 105 is 23.
Choosing a Method Under Time Pressure
Pick the shortest tool that fits the modulus and the base. Check gcd first, because Fermat and Euler do not apply when the base shares a factor with the modulus.
import math
print(pow(2, 100, 13)) # 3, by Fermat: 100 mod 12 = 4
print(pow(7, 100, 10)) # 1, by Euler: phi(10) = 4
print(math.factorial(100) % 101) # 100, by Wilson's theorem
x = next(x for x in range(105) if x % 3 == 2 and x % 5 == 3 and x % 7 == 2)
print(x) # 23, by the Chinese Remainder TheoremExercise
What is 3^50 mod 17?
Show answer
17 is prime and does not divide 3, so 3^16 ≡ 1 (mod 17). Since 50 mod 16 = 2, we get 3^50 ≡ 3^2 = 9 (mod 17). The answer is 9.