//互质
void ex_gcd(int a, int b, int &x, int &y){
if(!b){
x = 1,y = 0;
return ;
} ex_gcd(b, a%b, y, x);y -= (a / b) * x;
}
LL CRT(int remid[], int MOD[])
{
LL M = 1;
LL ans = 0;
for(int i = 0; i < n; i++)M *= MOD[i];
for(int i = 0; i < n; i++)
{
LL t = M / MOD[i];
int x, y;
ex_gcd(t, MOD[i], x, y);
ans += remid[i] * t * x;
ans %= M;
}
ans = (ans + M) % M;
return ans;
}
//非互质
ll c[N],m[N],ans;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(b==0){x=1;y=0;return a;}
ll gcd=exgcd(b,a%b,x,y);
ll t=x;
x=y; y=t-a/b*y;
return gcd;
}
ll CRT()
{
ll x,y;
ll M=m[1],ans=c[1];
for(int i=2;i<=n;i++)
{
ll a=M,b=m[i],XC=(c[i]-ans%b+b)%b;
ll gcd=exgcd(a,b,x,y),bg=b/gcd;
if(XC%gcd!=0) return -1;
x=mul(x,XC/gcd,bg);
ans+=x*M;
M*=bg;
ans=(ans%M+M)%M;
}
return (ans%M+M)%M;
}
int main(){
//freopen("in.txt","r",stdin);
cin>>n;
for(int i=1;i<=n;i++)sc("%lld%lld",&m[i],&c[i]);
o(CRT());
}
原理:
设
,
,有解的时候