线性同余方程模板( A+C*x=B(mod D) )

void extendgcd(long long a,long long b,long long &d,long long &x,long long &y)
{
    if(b==0){d=a;x=1;y=0;return;}
    extendgcd(b,a%b,d,y,x);
    y -= x*(a/b);
}

//求解A+C*x=B(mod D),返回最小非负整数x
long long ModX(long long A,long long B,long long C,long long D)
{
    if(A==B)
    {
        return 0;
    }

    if(C==0)
    {
        return -1;
    }
    long long x,y,tmpd;
    extendgcd(C,D,tmpd,x,y);
    if( (B-A)%tmpd != 0 )
    {
        return -1;
    }
    else
    {
        x *= (B-A)/tmpd;
        long long mod = D/tmpd;
        x = (x%mod+mod)%mod;
        return x;
    }
}

 

posted @ 2015-11-24 21:19  chenhuan001  阅读(448)  评论(0编辑  收藏  举报