Loading

【模板】 拓展中国剩余定理 EXCRT

ll ai[maxn], bi[maxn];

ll mul(ll a, ll b, ll mod)
{
    ll res = 0;
    while (b > 0)
    {
        if (b & 1) res = (res + a) % mod;
        a = (a + a) % mod;
        b >>= 1;
    }
    return res;
}

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

ll excrt()
{
    ll x, y, k;
    ll M = bi[1], ans = ai[1];
    for (int i = 2; i <= n; i++)
    {
        ll a = M, b = bi[i], c = (ai[i] - ans % b + b) % b;
        ll gcd = exgcd(a, b, x, y), bg = b / gcd;
        if (c % gcd != 0) return -1;

        x = mul(x, c / gcd, bg);
        ans += x * M;
        M *= bg;
        ans = (ans % M + M) % M;
    }
    return (ans % M + M) % M;
}

 

posted @ 2020-07-24 00:01  MQFLLY  阅读(157)  评论(0编辑  收藏  举报