中国剩余定理

中国剩余定理

对同余方程组:

x=a1(mod m1)

x=a2(mod m2)

.

x=ak(mod mk)

(m1,m2,...,mn互质)

则解x=M1*inv(M1,m1)+...+Mn*inv(Mn,mn) (mod m)

(其中m=m1*m2*...*mn=mi*Mi,   Mi=m/mi)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<math.h>
#include<cctype>
#define ll long long
#define REP(i,a,b) for(int (i)=(a);(i)<=(b);(i)++)
#define REPP(i,a,b,t) for(int (i)=(a);(i)<=(b);(i)+=(t))
#define PII pair<int,int>
#define fst first
#define snd second
#define MP make_pair
#define PB push_back
#define RI(x) scanf("%d",&(x))
#define RII(x,y) scanf("%d%d",&(x),&(y))
#define RIII(x,y,z) scanf("%d%d%d",&(x),&(y),&(z))
#define DRI(x) int (x);scanf("%d",&(x))
#define DRII(x,y) int (x),(y);scanf("%d%d",&(x),&(y))
#define DRIII(x,y,z) int (x),(y),(z);scanf("%d%d",&(x),&(y),&(z))
#define RS(x) scanf("%s",s)
#define RSS(x,y) scanf("%s%s",x,y)
#define DRS(x) char x[maxn];scanf("%s",x)
#define DRSS(x,y) char x[maxn],y[maxn];scanf("%s%s",x,y)
#define MS0(a) memset((a),0,sizeof((a)))
#define MS1(a) memset((a),-1,sizeof((a)))
#define MS(a,b) memset((a),(b),sizeof((a)))
#define ALL(v) v.begin(),v.end()
#define SZ(v) (v).size()

using namespace std;

const int maxn=1000100;
const int INF=(1<<29);
const double EPS=0.0000000001;
const double Pi=acos(-1.0);

int n;
ll a[maxn],m[maxn];
ll x;
ll M,Mt[maxn];

ll qpow(ll n,ll k,ll p)
{
    ll res=1;
    while(k){
        if(k&1) res=(res%p)*(n%p)%p;
        n=(n%p)*(n%p)%p;
        k>>=1;
    }
    return res;
}

ll inv(ll a,ll m)
{
    return qpow(a,m-2,m);
}

int main()
{
    DRI(T);
    while(T--){
        RI(n);
        REP(i,0,n-1) cin>>a[i]>>m[i];
        M=1;
        REP(i,0,n-1) M*=m[i];
        REP(i,0,n-1) Mt[i]=M/m[i];
        x=0;
        REP(i,0,n-1) x=((x%M)+(Mt[i]*inv(Mt[i],m[i])*a[i]%M))%M;
        cout<<x<<endl;
    }
    return 0;
}
View Code

 

posted @ 2015-06-17 22:37  __560  阅读(197)  评论(0编辑  收藏  举报