China remainder theorem coprime edition
The M1,M2,M3,...,MK is a positive integer of 22 biotin, i.e. gcd (MI,MJ) =1,i!=j,i,j=1,2,3,..., K.
Then the same residual equation group:
x = A1 (mod n1)
x = A2 (mod n2)
...
x = AK (mod nk)
modulo [N1,n2,... NK] has a unique solution, that is, in the sense of [N1,n2,..., NK], there is a unique x that satisfies:
x = AI mod [n1,n2,..., nk], i=1,2,3,..., K.
The solution can be written in this form:
x = Sigma (ai* mi*mi ') mod (N)
Where N=n1*n2*...*nk,mi=n/ni,mi ' is the inverse of mi in modulo ni multiplication.
Example Codevs 3990 China remainder theorem 2
/*Author: Best title: p3990 China remainder theorem 2*/#include<iostream>#include<cstdio>#include<cstring>#definell Long Longusing namespacestd;ll n,l,r,b[ One],m[ One],m[ One],mi[ One],s=1, Ans,sum,x,y;voidE_GCD (ll a,ll b) {if(!B) {x=1; y=0;return;} E_GCD (B,a%B);inttmp=x;x=y;y=tmp-a/b*y;}intMain () {CIN>>n>>l>>S; for(intI=1; i<=n;i++) Cin>>m[i]>>b[i],s*=M[i]; for(intI=1; i<=n;i++) M[i]=s/M[i]; for(intI=1; i<=n;i++) {x=y=0; E_GCD (M[i],m[i]); Mi[i]= (X+m[i])%M[i]; } for(intI=1; i<=n;i++) ans= (Ans+m[i]*mi[i]%s*b[i])%s; if(ans<l| | ANS>R) ans=sum=0; ElseSum= (R-ans)/s+1; cout<<sum<<endl<<ans; return 0;}
Chinese remainder theorem non-coprime version
Example HUD 1573 x problem
#include <iostream>#include<cstdio>#include<cstring>#definell Long Longusing namespacestd;ll t,n,m,a[ One],b[ One],X,Y,GCD;voidE_GCD (ll ai,ll bi) {if(!BI) {x=1; y=0; Gcd=ai;return;} E_GCD (Bi,ai%i); LL TMP=x;x=y;y=tmp-ai/bi*y;}intMain () {CIN>>u; while(t--) {cin>>n>>m; for(intI=1; i<=m;i++) cin>>A[i]; for(intI=1; i<=m;i++) cin>>B[i]; intfalg=0; ll a1=a[1],b1=b[1]; for(intI=2; i<=m;i++) {ll A2=a[i],b2=B[i]; E_GCD (A1,A2); if((B2-B1)%GCD) {falg=1; Break;} X*= ((B2-B1)/GCD); ll t=a2/GCD; X= (x%t+t)%t;b1+=a1*x; A1= (A1*A2/GCD); b1= (B1%A1+A1)%A1; } if(Falg| | B1>n) cout<<"0"<<Endl; Elsecout<< (N-B1)/a1+1-(!b1?)1:0) <<Endl; }}
Chinese remainder theorem coprime and non-coprime version