同餘方程組(EXCRT)(luogu4777)

#include<cstdio> #include<algorithm>
#define ll long long
using namespace std; ll k; ll a1,r1; ll a2,r2; ll x,y; ll g; void init() { scanf("%lld",&k); } void exgcd(ll a,ll b) { if(b==0) { x = 1; y = 0; }else { exgcd(b,a%b); ll t = x; x = y; y = t-a/b*x; } } void gcd(ll x,ll y) { if(y==0) { g = x; return ; } gcd(y,x%y); } ll ksc(ll x,ll y,ll mod) { ll ans = 0,kk=1; if(x<0)x=-x,kk=-kk; if(y<0)y=-y,kk=-kk; while(y) { if(y%2) { ans = (ans+x)%mod; } y>>=1; x = (x+x)%mod; } return ans%mod*kk; } void solve() { scanf("%lld%lld%lld%lld",&a1,&r1,&a2,&r2); ll a,b,c; a = a1; b = a2; c = r2-r1;//ax=c(mod b)
 gcd(a,b); if(c%g!=0) { printf("-1\n"); return ; } a = a/g; b = b/g; c = c/g; exgcd(a,b); x = (ksc(x,c,b)+b)%b;//x = k0
     c = x*a1+r1; gcd(a1,a2); b = a1/g*a2; k = k-2; r1 = c; a1 = b; while(k--) { scanf("%lld%lld",&a2,&r2); ll a,b,c; a = a1; b = a2; c = r2-r1;//ax=c(mod b)
 gcd(a,b); if(c%g!=0) { printf("-1\n"); return ; } a = a/g; b = b/g; c = c/g; exgcd(a,b); x =(ksc(x,c,b)+b)%b;//x = k0
         c = x*a1+r1; gcd(a1,a2); b = a1/g*a2; r1 = c; a1 = b; } exgcd(1,a1); x = (ksc(x,r1,a1)+a1)%a1; printf("%lld\n",x); } int main() { init(); solve(); return 0; }
相關文章
相關標籤/搜索