扩展欧几里得定理的应用:
/
//扩展中国剩余定理,可以模非质数的形式
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
int n;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b){
x = 1;
y = 0;
return a;
}
ll re = exgcd(b,a%b,x,y),temp = y;
y = x - (a/b)*y;
x= temp;
return re;
}
ll m[maxn],a[maxn];
ll ExChina()
{
ll M = m[1],A = a[1],t,d,x,y;
for(int i =2;i<=n;i++)
{
d = exgcd(M,m[i],x,y);
if((a[i]-A)%d) return -1;//无解
//求x ,扩展欧几里得定理的应用
x*=(a[i]-A)/d; //先让x乘(b1-b2)
t = m[i]/d;
x = x*(x%t+t)%t;
//相当于k = (a1*x1)+b1 , M是公倍数lcm
A = M*x+A,M = M/d*m[i],A%=M;
}
A = (A%M+M)%M;//这里让他输出都为正数
return A;
}
int main()
{
int i,j;
while(scanf("%d",&n)!=EOF){
for(i=1;i<=n;i++)scanf("%lld%lld",&m[i],&a[i]);
printf("%lld\n",ExChina());
}
return 0;
}