线性同余方程
解线性同余方程的简单应用,注意要把数据读完再输出-1。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
LL n;
LL exgcd(LL a,LL &x,LL b,LL &y){
if (!b){
x=1; y=0; return a;
}
LL r=exgcd(b,y,a%b,x);
y-=(a/b)*x;
return r;
}
int main(){
while (scanf("%lld",&n)!=EOF){
LL a,m; bool f=false;
scanf("%lld%lld",&a,&m);
for (LL i=1;i<n;i++){
LL a1,m1,x,y;
scanf("%lld%lld",&a1,&m1);
LL r=exgcd(a,x,a1,y),c=m1-m;
if (c%r) f=true;
LL t=a1/r;
x=(x*(c/r)%t+t)%t;
m+=a*x;
a*=(a1/r);
}
if (f) printf("-1\n");
else printf("%lld\n",m);
}
return 0;
}