中国剩余定理 Chinese remainder theorem(CRT)

来源:互联网 发布:慢跑鞋哪个牌子好 知乎 编辑:程序博客网 时间:2024/05/21 19:34

中国剩余定理又称孙子定理, 主要是为了解线同余方程组

  1. x ≡ a( mod  m)
  2. x ≡ a( modm)
  3. x a( modm
  4.        .........
  5. x ≡ a( modm)

成立条件是m1,m2, ... ,mn 两两互质, 则对任意的整数:a1,a2, ... ,an,方程组S 有解 

并且可以构造出通解  x =  (a1*t1*Ma2*t2*Ma3*t3*M+...+ an*tn*M) +  KM 

在模M的意义下 x =a1*t1*Ma2*t2*Ma3*t3*M+...+ an*tn*M

M = m*m*m* ... *m,

M= M / m

      t
 M
m
意义下的逆元, 即 tM≡ 1  ( mod m

显然带入方程组中可验证正确性,证明略

//非递归的扩展欧几里德算法//返回a、b的gcd,同时x、y满足ax+by=gcdint_t _exEuclid(int_t a,int_t b,int_t&x,int_t&y){    int_t x0 = 1, y0 = 0;    int_t x1 = 0, y1 = 1;    x = 0; y = 1;    int_t r = a % b;    int_t q = ( a - r ) / b;    while( r ){        x = x0 - q * x1;        y = y0 - q * y1;        x0 = x1; y0 = y1;        x1 = x; y1 = y;        a = b; b = r; r = a % b;        q = ( a - r ) / b;    }    return b;}//求a相对于p的逆元,a、p互质才存在逆元int_t _inv(int_t a,int_t p){    int_t x,y;    int_t r = _exEuclid(a,p,x,y);    if ( r != 1 ) return 0;    x = x % p;    if ( x < 0 ) x += p;    return x;}// 中国剩余定理int_t CRT( int n ,int_t  *remain, int_t *mod){    int_t M = 1, x = 0;    for (int i = 0;i < n;++i)        M *= mod[i];    for ( int i = 0;i < n;++i ){        M /= mod[i];        x +=  remain[i] * M * _inv(M,mod[i]) ;        M *= mod[i];    }    return x;}





0 0
原创粉丝点击