广义中国剩余定理

Generalized Chinese Remainder Theorem

来源:http://www.cut-the-knot.org/blue/chinese.shtml (IE only)

Theorem 1
引用

Two simultaneous congruences

  n = n1 (mod m1) and
  n = n2 (mod m2) 

are only solvable when n1 = n2 (mod gcd(m1, m2)). The solution is unique modulo lcm(m1, m2).

(When m1 and m2 are coprime their gcd is 1. By convention, a = b (mod 1) holds for any a and b.)

Proof
引用

By a generalization of the Euclid's algorithm, there are integers s and t such that

  tm1 + sm2 = gcd(m1, m2). 

Since n2 - n1 = 0 (mod gcd(m1, m2)), for some, possibly different t and s,

(2) tm1 + sm2 = n2 - n1. 

Then n = tm1 + n1 = -sm2 + n2 satisfies both congruences in the theorem. This proves the existence of a solution.

To prove the uniqueness part, assume n and N satisfy the two congruences. Taking the differences we see that

  N - n = 0 (mod m1) and N - n = 0 (mod m2) 

which implies N - n = 0 (mod lcm(m1, m2)).

As was previously stated, a more general theorem can now be proved by induction.


Theorem 2
引用

The simultaneous congruences (1)

  n = n1 (mod m1)
  n = n2 (mod m2)
...
n = nk (mod mk) 
are only solvable when ni = nj (mod gcd(mi, mj)), for all i and j, i ≠ j. The solution is unique modulo lcm(m1, m2, ..., mk).


具体算法:
首先以两个同余方程组成的方程组为例:
  n = n1 (mod m1) and
  n = n2 (mod m2)
有解的前提条件是gcd(m1, m2) | (n2 - n1)
1) 用扩展欧几里德算法计算t * m1 + s * m2 = gcd(m1, m2) = d
2) 计算tt, ss使其满足tt * m1 + ss * m2 = n2 - n1
具体方法是tt = t * (n2 - n1) / d,ss = s * (n2 - n1) / d
3) 那么nn = tt * m1 + n1 = -ss * m2 + n2 (这两个用哪个都行)
4) 我们已经把两个同余方程组变成了一个:
  n = nn (mod LCM(m1, m2))
重复这个过程,每次合并两个方程,就可以解决整个方程组了


update: 算法艺术与信息学竞赛第230页有讲解,很清晰
update2: 题目hdu1930 hdu1370 jlu1167

你可能感兴趣的:(算法,IE,J#)