传送门:点击打开链接
中国剩余定理的第一个模板。
这个模板比较简单,求的是一系列的模方程组
x % m = a
用这个模板有几个前提。
1:必须两两互质
2:全部乘起来不能爆long long
#include<map>
#include<set>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define FIN freopen("input.txt","r",stdin)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int MX = 1000 + 5;
LL exgcd(LL a, LL b, LL &x, LL &y) {
if(b == 0) {
x = 1; y = 0;
return a;
}
LL r = exgcd(b, a % b, x, y);
LL t = y;
y = x - a / b * y;
x = t;
return r;
}
/*x % m = a*/
LL china(int n, int *m, int *a) {
LL M = 1, d, y, x = 0;
for(int i = 0; i < n; i++) M *= m[i];
for(int i = 0; i < n; i++) {
LL w = M / m[i];
d = exgcd(m[i], w, d, y);
x = (x + y * w * a[i]) % M;
}
return (x + M) % M;
}
int A[MX], B[MX];
int main() {
FIN;
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d%d", &A[i], &B[i]);
}
printf("%I64d\n", china(n, A, B));
return 0;
}