中国剩余定理 孙子定理(互质与不互质) FZU1402(互质) POJ2891(不互质)

中国剩余定理

先看个互质的

\left\{\begin{matrix} x \equiv a_1 (mod $ $ m_1) \\x \equiv a_2 (mod $ $ m_2) \\... \\x \equiv a_n (mod $ $ m_n) \end{matrix}\right.

解得 x = \sum _{i=1}^n a_i \cdot \frac{M}{m_i} $//$(M = \sum _{i=1}^{n}m_i)   


/*
 *中国剩余定理 互质
 */
#include 
#include 
#include 

using namespace std;
typedef long long LL;
///n个mi互质
const LL maxn = 20;
LL a[maxn], m[maxn], n;

LL ex_gcd(LL a, LL b, LL &x, LL &y){
    if (b == 0){
        x = 1; y = 0;
        return a;
    }
    LL res = ex_gcd(b, a % b, y, x);
    y = y - a/b * x;
    return res;
}

LL CRT(LL a[], LL m[], LL n)
{
    LL M = 1;
    for (int i = 0; i < n; i++) M *= m[i];
    LL ret = 0;
    for (int i = 0; i < n; i++)
    {
        LL x, y;
        LL tm = M / m[i];
        ex_gcd(tm, m[i], x, y);
        ret = (ret + tm * x * a[i]) % M;//x是mi的逆元
    }
    return (ret + M) % M;
}

int main(){
    while (~scanf("%d", &n)){
        for (int i = 0; i < n; i++){
            scanf("%d%d", &m[i], &a[i]);
        }
        cout << CRT(a, m, n) << endl;
    }
    return 0;
}

再看个不互质的

中国剩余定理 孙子定理(互质与不互质) FZU1402(互质) POJ2891(不互质)_第1张图片

/*
 *中国剩余定理 不互质
 */
#include
#include
using namespace std;
#define LL long long
LL ex_gcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1;y=0;
        return a;
    }
    LL r=ex_gcd(b,a%b,x,y);
    LL t=x;
    x=y;
    y=t-a/b*y;
    return r;
}

const LL maxn = 1000;
LL a[maxn], m[maxn], n;
LL CRT(LL a[], LL m[], LL n) {
    if (n == 1) {
        if (m[0] > a[0]) return a[0];
        else return -1;
    }
    LL x, y, d;
    for (int i = 1; i < n; i++) {
        if (m[i] <= a[i]) return -1;
        d = ex_gcd(m[0], m[i], x, y);
        if ((a[i] - a[0]) % d != 0) return -1;
        LL t = m[i] / d;
        x = ((a[i] - a[0]) / d * x % t + t) % t; //之前的x是mi的逆元,之后是推导中的K
        a[0] = x * m[0] + a[0];
        m[0] = m[0] * m[i] / d;
        a[0] = (a[0] % m[0] + m[0]) % m[0];
    }
    return a[0];
}

int main ()
{
   LL T;
   while( ~scanf("%lld",&T) )
   {
       for(int i=0; i

 

你可能感兴趣的:(模板,acm,数学,模板,中国剩余定理,数论)