Luogu P3868 [TJOI2009]猜数字
题目链接 \(Click\) \(Here\)
中国剩余定理的板子。小心取模。
#include <bits/stdc++.h>
using namespace std;
const int N = 11;
#define int long long
int n, M = 1, a[N], b[N], t[N], ans;
int fmul (int x, int y, int mod) {
int res = 0;
while (y) {
if (y & 1) {
res = (res + x) % mod;
}
x = (x + x) % mod;
y >>= 1;
}
return res;
}
void exgcd (int a, int b, int &x, int &y) {
if (b == 0) {x = 1, y = 0; return;}
exgcd (b, a % b, x, y);
int xx = y, yy = x - (a / b) * y;
x = xx, y = yy;
}
signed main () {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) cin >> b[i];
for (int i = 1; i <= n; ++i) a[i] = ((a[i] % b[i]) + b[i]) % b[i];
for (int i = 1; i <= n; ++i) M *= b[i];
for (int i = 1; i <= n; ++i) {
exgcd (M / b[i], b[i], t[i], t[0]);
t[i] = ((t[i] % b[i]) + b[i]) % b[i];
ans = (ans + fmul (fmul (M / b[i], t[i], M), a[i], M)) % M;
}
cout << ((ans % M) + M) % M << endl;
}