Consider a congruence equation
\ [\ begin {cases} x \ equiv a_1 \ (mod \ b_1) \\ x \ equiv a_2 \ (mod \ b_2) \\\ quad \ quad \ quad \ vdots \\ x \ equiv a_n \ (mod \ b_n) \ end {cases} \]
Wherein \ (b_1, b_2, \ dots , b_n \) pairwise quality.
Order \ (m = \ Prod \ limits_ {I =. 1} ^ n-B_i \) , \ (M_i = \ FRAC {m} {B_i} \) , \ (t_i \) is the congruence equation \ (xM_i \ equiv 1 (mod \ b_i) \) \ of a solution
Then the solution for the equations above that \ (\ SUM \ limits_. 1 = {I}} ^ {n-a_i M_i t_i \) .
prove:
Consider \ (\ \ SUM) in a \ (I \) , for the \ (k = i \) apparently \ (a_i M_i t_i \ equiv a_k \ (MOD \ b_k) \) , if the \ (k \ not I = \) , then \ (a_i M_i t_i \ equiv 0 \ (MOD \ b_k) \) (as \ (M_i \) other (B \) \ product).
Therefore, the above (\ Sigma \) \ in \ (n-\) entry will meet each equation, would not affect the other, so that \ (x = \ sum \ limits_ {i = 1} ^ {n} a_i M_i t_i \) is the set of legal solutions.
QED.
Further, \ (X \) is the (mod \ m \) \ Solutions of the sense, i.e., solution set may be expressed as \ (\ + {X km: K \ in \ the Z \} \) .
\(Code\)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mult(ll a,ll b,ll c){
if (b>a) swap(a,b);
ll ret=0; for (;b;b>>=1,a=a*2%c) if (b&1) ret=(ret+a)%c;
return ret;
}
void exgcd(ll a,ll b,ll &x,ll &y){
if (b==0){x=1,y=0;return;}
else{
exgcd(b,a%b,x,y);
ll tmp=x; x=y; y=tmp-a/b*x;
}
}
ll a[110],b[110]; int n;
ll CRT(){
ll m=1; for (int i=1;i<=n;i++)m*=b[i];
for (int i=1;i<=n;i++) a[i]=(a[i]%m+m)%m;
ll ans=0;
for (int i=1;i<=n;i++){
ll Mi=m/b[i],t,tmp;
exgcd(Mi,b[i],t,tmp);
t=(t%m+m)%m;
ans=(ans+mult(Mi,mult(t,a[i],m),m))%m;
}
return ans;
}
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%lld",&a[i]);
for (int i=1;i<=n;i++) scanf("%lld",&b[i]);
printf("%lld\n",CRT());
return 0;
}
To be filled: Extending Chinese remainder theorem \ (ExCRT \)