/*
问题:求解 n个方程:x=a[i](mod m[i]) (0<=i<n) 的x
类型:中国剩余定理
吐槽:这个模版要求m[i]之间两两互质啊QAQ
*/
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn = 105;
void ex_gcd(LL a, LL b, LL &x, LL &y, LL &d){
if (!b) {d = a, x = 1, y = 0;}
else{
ex_gcd(b, a % b, y, x, d);
y -= x * (a / b);
}
}
LL inv(LL t, LL p){//如果不存在,返回-1
LL d, x, y;
ex_gcd(t, p, x, y, d);
return d == 1 ? (x % p + p) % p : -1;
}
//n个方程:x=a[i](mod m[i]) (0<=i<n)
LL china(int n, LL *a, LL *m){
LL M = 1, ret = 0;
for(int i = 0; i < n; i ++) M *= m[i];
for(int i = 0; i < n; i ++){
LL w = M / m[i];
ret = (ret + w * inv(w, m[i]) * a[i]) % M;
}
return (ret + M) % M;
}
LL m[maxn],a[maxn];//m[i]是取模的数,两两互质;a[i]是余数
int main()
{
int n;//n个数
cin>>n;
for(int i=0;i<n;i++){
cin>>m[i]>>a[i];
}
cout<<china(n,a,m)<<endl;
/*
3
3 2
5 3
7 2
*/
return 0;
}
中国剩余定理模版【中国剩余定理】
最新推荐文章于 2022-11-01 22:50:30 发布