中国剩余定理 CRT
若在序列
的解。注意到,对于第
再求
这说明每一个解都不影响其他方程,可以独立求解再求和。因此有
对所有的解累加求和得到方程组的解
cpp
ll crt(const vector<ll> &aa, const vector<ll> &nn) {
ll prod = 1, ret = 0, n = aa.size();
for (auto ni : nn)
prod *= ni;
for (int i = 0; i < n; i++) {
ll m = prod / nn[i];
ret += aa[i] * m * inv(m, nn[i]);
ret %= prod;
}
return ret;
}
ll crt(const vector<ll> &aa, const vector<ll> &nn) {
ll prod = 1, ret = 0, n = aa.size();
for (auto ni : nn)
prod *= ni;
for (int i = 0; i < n; i++) {
ll m = prod / nn[i];
ret += aa[i] * m * inv(m, nn[i]);
ret %= prod;
}
return ret;
}