Welcome to a fascinating journey into the heart of number theory! Today, we'll be exploring the Chinese Remainder Theorem ā a powerful tool that solves simultaneous congruences, making it an essential skill for every programmer.
The Chinese Remainder Theorem (CRT) is a method used to solve a system of linear congruences, connecting the solutions of individual congruences.
Here's a simple way to understand it:
If you have multiple numbers (moduli) that are pairwise coprime, you can find a single solution that works for all of them simultaneously. Let's dive deeper into the world of congruences and coprime numbers.
In mathematics, a congruence is an equation of the form a ā” b (mod m), where a and b are integers, m is a positive integer, and ā” denotes congruence.
This means that a and b leave the same remainder when divided by m. For example:
Two numbers are called coprime or relatively prime if their greatest common divisor (GCD) is 1. In other words, they share no common factors other than 1.
For example:
The CRT is essential in solving complex problems, such as scheduling jobs that require different amounts of time on multiple machines, or encoding messages in a way that can be decoded using multiple keys.
Now that we've covered the basics, let's move on to solving a system of linear congruences using the Chinese Remainder Theorem!
To solve a system of linear congruences using CRT, follow these steps:
m_i).m_i).x).Let's solve the following system of linear congruences:
x ā” 2 (mod 3)x ā” 3 (mod 4)x ā” 2 (mod 3)x ā” 3 (mod 4)m_i) š”m_1 = 3, the multiplicative inverse of 3 is 2 (because 3 * 2 ā” 1 (mod 3)).m_2 = 4, the multiplicative inverse of 3 is 3 (because 3 * 3 ā” 1 (mod 4)).2 * x ā” 1 (mod 3)3 * x ā” 1 (mod 4)The CRT formula is:
x ┠Σ (m_i * (s_i * t_i)) (mod Π(m_i))
Ī£ denotes summation.m_i are the moduli (3 and 4 in this case).s_i are the solutions to the congruences with the multiplicative inverses (2 and 3 in this case).t_i are the time variables (1 for each congruence in this case).Ī denotes the product of the moduli.Substituting our values:
x ā” (3 * 2 * 1) + (4 * 3 * 1) (mod 3 * 4)
x) š”x ā” 6 + 12 (mod 12)
x ā” 18 (mod 12)
Now we have a solution for the system of linear congruences:
x ā” 18 (mod 12)Here's a Python implementation of the Chinese Remainder Theorem to solve more complex problems:
def mod_inverse(a, m):
m0 = m
new_a = a % m
m2 = m0
while new_a != 1:
q = m0 // new_a
m1 = m0 % new_a
m0, new_a = new_a, m1
m1, m2 = m2, m0
return m2 if m2 < m0 else m2 - m0
def chinese_remainder(n, rem):
sum = 0
prod = reduce(lambda a, b: a * b, n)
for n_i, r_i in zip(n, rem):
p = prod // n_i
sum += p * (r_i + mod_inverse(p, n_i) * (prod // n_i))
return sum % prod
# Example usage
moduli = [3, 4]
remainders = [2, 3]
print(chinese_remainder(moduli, remainders)) # Output: 18What does the Chinese Remainder Theorem do?
What is a multiplicative inverse (modulo `m`)?