Fork me on GitHub

中国剩余定理解同余方程组

ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(!b)
    {
        x = (ll)1,y = (ll)0;
        return a;
    }
    ll r = exgcd(b,a%b,x,y);
    ll t = x;
    x = y;
    y = t - a/b*y;
    return r;
}

//n个方程: x = a[i](mod m[i]) (0<=i<n)
ll china(int n,int *a,int *m)
{
    ll M = 1,d,y,x = 0;
    int i;
    for(i=0;i<n;i++)
        M *= m[i];
    for(i=0;i<n;i++)
    {
        ll w = M/m[i];
        d = exgcd(m[i],w,x,y)
        x = (x + y*w*a[i])%M;
    }
    return (x+M)%M;
}

 

posted @ 2014-06-28 21:30  whatbeg  阅读(456)  评论(0编辑  收藏  举报