扩展中国剩余定理
csh7306jjj · · 个人记录
#include<bits/stdc++.h>
#define int __int128
#define ll long long
#define D(x) cout<<#x<<": "<<x<<"\n";
using namespace std;
inline int R() {int x = 0;bool f = 1;char ch = getchar();while (!isdigit(ch)) f = ch == '-' ? 0 : 1, ch = getchar();while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();return f ? x : -x;}
inline void W(int x) {if (x < 0) putchar('-'), x = -x;if (x > 9) W(x / 10);putchar(x % 10 + 48);}
const int N=4e6+10;
int n,a,b,x,y;
ll A,AA,B,BB,d;
int gcd(int x,int y){
if(x%y==0) return y;
return gcd(y,x%y);
}
int lcm(int x,int y){return x/gcd(x,y)*y;}
inline void exgcd(int a,int b,int &x,int &y){
if(!b){ d=a;x=1;y=0;}
else{
exgcd(b,a%b,x,y);
int t=x;x=y;y=t-(a/b)*y;
}
}
void exchina(){
exgcd(a,A,x,y);
ll c=B-b;
if(c%d) {
W(-1);
exit(0);
}
x=x*c/d%(A/d);
if(x<0) x+=A/d;
ll m=lcm(a,A);
b=(a*x+b)%m;
if(b<0) b+=m;
a=m;
}
signed main() {
n=R();
for(ll i=1;i<=n;i++) {
AA=R(),BB=R();
A=AA;B=BB;
if(i>1) exchina();
else{
a=A;
b=B;
}
}
W(b%a);
return 0;
}