[模板] 中国剩余定理
[证明] 待补充
//Writer:GhostCai && His Yellow Duck
#include<iostream>
using namespace std;
int exgcd(int a,int b,int &x,int &y){
if(b==0){
x=1,y=0;
return a;
}
int gcd=exgcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
return gcd;
}
int china(int *M,int *B,int k){
int x,b,a=0,m=1,mi;
for(int i=1;i<=k;i++) m*=M[i];
for(int i=1;i<=k;i++){
mi=m/M[i];
exgcd(M[i],mi,x,b);
a=(a+b*mi*B[i])%m;
}
if(a>0) return a;
else return a+m;
}
int main(){
int b[100],m[100];
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>b[i]>>m[i];
}
cout<<china(m,b,n);
}
本文来自博客园,作者:GhostCai,转载请注明原文链接:https://www.cnblogs.com/ghostcai/p/9247515.html