#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=4e6+10;
const int inf=0x3f3f3f3f;
LL exgcd(LL a,LL b,LL &x,LL &y)//扩展欧几里得
{
if(!b)
{
x=1;
y=0;
return a;
}
LL gcd=exgcd(b,a%b,y,x);
y-=a/b*x;
return gcd;
}
LL china(LL a[],LL m[],LL num)//x=a[i]%m[i]; num是方程的个数
{
LL n1=m[0],a1=a[0],n2,a2,k1,k2,x0,gcd,c;
for(int i=1; i<num; i++)
{
n2=m[i],a2=a[i];
c=a2-a1;
gcd=exgcd(n1,n2,k1,k2);//解得:n1*k1+n2*k2=gcd(n1,n2)
if(c%gcd)
{
// flag=1;
return -1;//无解
}
x0=c/gcd*k1;//n1*x0+n2*(c/gcd*k2)=c PS:k1/gcd*c错误!
LL t=n2/gcd;
if(t<0) t=-t;
x0=(x0%t+t)%t;//求n1*x0+n2*y=c的x0的最小解
a1+=n1*x0;
n1=n2/gcd*n1;
}
//所有的通解是 a1+k*n1(k为>=0的整数);
return ((a1%n1)+n1)%n1;
}
LL a[maxn],m[maxn];
int main()
{
LL n;
while(~scanf("%lld",&n))
{
for(int i=0; i<n; i++)
scanf("%lld%lld",&m[i],&a[i]);
printf("%lld\n",china(a,m,n));
}
}
中国剩余定理
最新推荐文章于 2024-12-25 18:28:40 发布