Chinese Remainder Theorem
Chinese Remainder Theorem
The Chinese Remainder Theorem (CRT) solves systems of simultaneous congruences. Given:
when , there is a unique solution modulo .
Historical Context
The theorem is named after the "Mathematical Classic of Sun Zi" (4th century AD), which posed: "We have things of which we do not know the number; if we count them by threes, we have two left over; by fives, we have three left over; by sevens, we have two left over. How many things are there?"
Solving with Extended GCD
Using Bezout's identity: find such that (using extended GCD). Then:
Equivalently, we can write it as:
def extended_gcd(a, b):
if b == 0:
return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
def crt(a1, m1, a2, m2):
g, s, t = extended_gcd(m1, m2)
modulus = m1 * m2 // g
x = (a1 + m1 * s * (a2 - a1) // g) % modulus
return x
# x ≡ 2 (mod 3), x ≡ 3 (mod 5) → x = 8
print(crt(2, 3, 3, 5)) # 8
# Verify: 8 % 3 = 2 ✓, 8 % 5 = 3 ✓
Verification
Always verify: if x = crt(a1, m1, a2, m2) then x % m1 == a1 and x % m2 == a2.
Generalization
CRT extends to any number of congruences, applying the two-congruence version iteratively. It also works when , but only if .
Your Task
Using an extended_gcd helper provided in the starter code, implement crt(a1, m1, a2, m2) that returns the unique satisfying both congruences.