poj 2115(线性同余方程。。。。。)

记错了一个定理。。。。无情的WA了。。。。。。最后求出的解要多n/d取模。。。。因为两个数不一定互素。。。。。。

一个定理: 设d=gcd(a,n),假定对整数x和y满足d=ax+by。 如果d | b,则方程ax=b(mod n)有一个解x0满足x0=x*(b/d) mod n 。特别的设e=x0+n, 方程ax=b(mod n)的最小整数解x1=e mod (n/d),最大整数解x2=x1+(d-1)*(n/d)。

#include<iostream>
using namespace std;
#define LL long long
LL ex_gcd(LL a,LL b,LL &x,LL &y){
    if(b==0){
        x=1,y=0;
        return a;
    }
    LL d=ex_gcd(b,a%b,x,y),t=x;
    x=y; y=t-a/b*y;
    return d;
}
LL mod(LL a,LL b,LL n){
    LL x,y,d,e;
    d=ex_gcd(a,n,x,y);
    if(b%d!=0) return -1;
    e=(x*(b/d))%n;
    while(e<0) e+=n/d; 
    return e%(n/d);
}
int main(){
    LL a,b,c,k,ans;
    while(scanf("%lld%lld%lld%lld",&a,&b,&c,&k) && (a+b+c+k) ){
        k=(1LL<<k);
        ans=mod(c,b-a,k);
        if(ans==-1)
            printf("FOREVER\n");
        else
            printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(poj 2115(线性同余方程。。。。。))