中国剩余定理(excrt) 模板

excrt板子题

 1 #include <cmath>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #define ll long long 
 6 #define N 100010
 7 #define rint register int
 8 #define ll long long 
 9 #define il inline
10 using namespace std;
11 //re
12 int n;
13 ll A[N],B[N];
14 ll qadd(ll x,ll y,const ll &mo){ll ans=0;while(y){if(y&1)ans=(ans+x)%mo;x=(x+x)%mo;y>>=1;}return ans;}
15 ll qpow(ll x,ll y,const ll &mo){ll ans=1;while(y){if(y&1)ans=(ans*x)%mo;x=(x*x)%mo;y>>=1;}return ans;}
16 ll exgcd(ll a,ll b,ll &x,ll &y){
17     if(b==0){x=1,y=0;return a;}
18     ll ans=exgcd(b,a%b,x,y);
19     ll t=x;x=y;y=t-a/b*y;
20     return ans;
21 }
22 ll excrt()
23 {
24     ll x,y,ans=A[1],M=B[1],bg;
25     for(int i=2;i<=n;i++)
26     {
27         ll a=M,b=B[i],c=(A[i]-ans%b+b)%b;
28         ll gcd=exgcd(M,b,x,y);bg=b/gcd;
29         if(c%gcd!=0) return -1;
30         x=qadd(x,c/gcd,bg);
31         ans+=x*M;
32         M*=bg;
33         ans=(ans%M+M)%M;
34     }
35     return ans;
36 }
37 
38 int main()
39 {
40     scanf("%d",&n);
41     for(int i=1;i<=n;i++)
42         scanf("%lld%lld",&B[i],&A[i]);
43     printf("%lld
",excrt());
44     return 0;
45 }
原文地址:https://www.cnblogs.com/guapisolo/p/9720176.html