中国剩余定理

洛谷P1495 https://www.luogu.com.cn/problem/P1495

ll exgcd(ll a, ll b, ll &x, ll &y)
{
    if(!b)
    {
        x = 1, y = 0;
        return a;
    }
    int d = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}

ll m[maxn], rest[maxn], n;   //M存储商,rest存储余数
ll China()
{
    ll M  = m[1], X = rest[1], x, y;    //假设此时X已经满足前i-1个等式, 即通解为 X + M * k
    for(int i = 2; i <= n; ++i)     //求解一个t1满足: X + t1*M ≡ rest[i] (mod m[i])
    {
        ll d = exgcd(M, m[i], x, y);   //即 t1*M + t2*m[i] = rest[i] - X,首先判断有无解
        if((rest[i] - X) % d) return -1;
        x = (rest[i] - X) / d * x % m[i];   //原先的x 为 t1*M+t2*m[i]=gcd(M, m[i]) = d的解
        X += M * x;   //更新特解X
        M *= m[i] / d;   //更新最小公倍数M
        X %= M;
    }
    return (X + M) % M;   //求得最小正整数解
}

 

posted @ 2020-12-11 20:28  .Ivorelectra  阅读(85)  评论(0编辑  收藏  举报