中国剩余定理用于求解 x≡ai(mod mi),当中mi两两互质,x有唯一解。
令M为mi的乘积,wi = M/mi,wi关于模mi的逆元为pi,即满足wi*pi + mi*qi = 1.
则上述方程组等价于 x≡ w1*p1*a1 + w2*p2*a2 +......+wk*pk*ak(mod M)................................................................①
验证: 当M = m1时, (w2*p2*a2 +......+wk*pk*ak)%m1 = 0,那么上式变为 x≡w1*p1*a1(mod m1),又由于w1的关于模m1的逆元是p1,那么进一步化简为x≡a1(mod m1)。
类比当M = m2,m3,,,,mk时。①式都是成立的。
因此求x,仅仅需求w1*p1*a1 + w2*p2*a2 +......+wk*pk*ak(mod M),当中wi,ai是已知的,pi可依据方程wi*pi + mi * qi = 1用扩展欧几里得求出。
#include #include