洛谷P1495 中国剩余定理(CRT)模板题

双倍经验


题目链接:https://www.luogu.com.cn/problem/P1495

解题思路:完全来自 oi wiki

注意:要开 __int128,不然会被 hack。

示例程序:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

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

ll inv(ll a, ll n) {
    ll x, y;
    assert(exgcd(a, n, x, y) == 1);
    return (x + n) % n;
}

ll crt(int k, ll a[], ll r[]) {
    ll n = 1;
    __int128 res = 0;
    for (int i = 1; i <= k; i++)
        n *= a[i];
    for (int i = 1; i <= k; i++) {
        ll m = n / a[i];
        __int128 c = (__int128) m % n * inv(m, a[i]) % n;
        (res += r[i] * c) %= n;
    }
    return (ll)res;
}

int k;
ll a[15], r[15];

int main() {
    scanf("%d", &k);
    for (int i = 1; i <= k; i++) {
        scanf("%lld%lld", a+i, r+i);
    }
    printf("%lld\n", crt(k, a, r));
    return 0;
}
posted @ 2026-05-04 15:45  quanjun  阅读(3)  评论(0)    收藏  举报