模板中国剩余定理

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

 

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<queue>
#include<stack>
#include<list>
#include<sstream>
#include<cstdio>
#define INF 0x3f3f3f3f
const int maxn = 1e6 + 5;
const double PI = acos(-1.0);
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

ll a[11], b[11];
int n;

inline ll gcd(ll a, ll b) {
    return b == 0 ? a : gcd(b, a % b);
}

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

ll chinaa() {
    ll M, ans;
    M = 1;
    ans = 0;
    for (int i = 1; i <= n; i++) M *= a[i];
    for (int i = 1; i <= n; i++) {
        ll m, p, d, y;
        m = M / a[i];
        d = exgcd(m, a[i], p, y);
        ans = (ans + m * p * b[i]) % M;
    }
    return ans < 0 ? ans + M : ans;
}

int main() {
    scanf("%d", &n);
    for (ll i = 1; i <= n; i++) {
        scanf("%lld%lld", &a[i], &b[i]);
    }
    printf("%lld", chinaa());
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/hznumqf/p/12327971.html