Chinese remainder theorem

/*

设a≡b[i](mod w[i)

i=1->n;  

We record k=w[1]*w[2]*w[3]*...*w[n]  

Then the system of equations has a unique solution in the sense of mod k congruence  

We let x=(k/w[i])*yi 

Then the equation is equivalent to (k/w[i])y≡1(mod w[i])  

Then the solution of the system of equations x0=b1x1+b2x2+...+bnxn(mod k)

*/

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long n,w[1010],b[1010],x,y,a,k=1,j;
long long exgcd(long long aa,long long bb)
{
    if(bb==0)
    {
        x=1;
        y=0;
        return aa;
    }
    long long _gcd=exgcd(bb,aa%bb);
    long long kk=x;
    x = y;
    y =kk-aa/bb* y;
    return _gcd;
} // Extended Euclidean to solve the equation 
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d%d",&w[i],&b[i]);
    for(int i=1;i<=n;i++)k*=w[i];//求k
    for(int i=1;i<=n;i++)
    {
        j=k/w[i];
        exgcd(w[i],j); /* Solve equation(k/w[i])y≡1(mod w[i]) */ 
    a =(a+y*j*b[i])%k ; /* accumulate */
   }
      if(a<0)a+=k;
      printf("%lld",a); 

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324743679&siteId=291194637