解高次同余方程A^x≡B(mod C)算法流程
S1:i从0到100循环,如果满足A^i≡B(mod C),那么i就为所求,否则继续S2;
S2:令d=0,D=1,执行如下循环:
while((tmp=gcd(A,C))!=1)
{
if(B%tmp) return -1; //无解
++d;
C/=tmp;
B/=tmp;
D=D*A/tmp%C;
}
S3:令m=ceil(sqrt(C));
S4:i从0到m继续执行将(i,A^i%C)插入到Hash表中;
S5:求得K=quick_mod(A,m,C),令i=0,如果i>m,执行S6;否则求DX≡B(mod C)在[ 0,C-1 ]的解,并在Hash表中查询,若查询到(假设是x),则返回i×m+x,否则D=DK%C,i=i+1继续循环;
S6:返回-1.
题目链接:http://poj.org/problem?id=3243
实现代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long LL;
const int maxn=65535;
struct Hash
{
int a,b,next;
}hash[maxn<<1];
int flg[maxn+66];
int top,idx;
void ins(int a,int b)
{
int k=b&maxn;
if(flg[k]!=idx)
{
flg[k]=idx;
hash[k].next=-1;
hash[k].a=a;
hash[k].b=b;
return ;
}
while(hash[k].next!=-1)
{
if(hash[k].b==b) return ;
k=hash[k].next;
}
hash[k].next=++top;
hash[top].next=-1;
hash[top].a=a;
hash[top].b=b;
}
int find(int b)
{
int k=b&maxn;
if(flg[k]!=idx) return -1;
while(k!=-1)
{
if(hash[k].b==b) return hash[k].a;
k=hash[k].next;
}
return -1;
}
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int exgcd(int a,int b,int &x,int &y)
{
int t,ret;
if(!b)
{
x=1,y=0;
return a;
}
ret=exgcd(b,a%b,x,y);
t=x,x=y,y=t-a/b*y;
return ret;
}
int Inval(int a,int b,int n)
{
int x,y,e;
exgcd(a,n,x,y);
e=(LL)x*b%n;
return e<0?e+n:e;
}
int pow_mod(LL a,int b,int c)
{
LL ret=1;
a%=c;
while(b)
{
if(b&1) ret=ret*a%c;
a=a*a%c;
b>>=1;
}
return ret;
}
int BabyStep(int A,int B,int C)
{
top=maxn;
++idx;
LL buf=1%C,D=buf,K;
int i,d=0,tmp;
for(i=0;i<=100;buf=buf*A%C,i++)
if(buf==B) return i;
while((tmp=gcd(A,C))!=1)
{
if(B%tmp) return -1; //无解
++d;
C/=tmp;
B/=tmp;
D=D*A/tmp%C;
}
int M=(int)ceil(sqrt((double)C));
for(buf=1%C,i=0;i<=M;buf=buf*A%C,i++) ins(i,buf);
for(i=0,K=pow_mod((LL)A,M,C);i<=M;D=D*K%C,i++)
{
tmp=Inval((int)D,B,C);
int w;
if(tmp>=0&&(w=find(tmp))!=-1)
return i*M+w+d;
}
return -1;
}
int main()
{
int A,B,C;
while(scanf("%d%d%d",&A,&C,&B)!=EOF,A||B||C)
{
B%=C;
int tmp=BabyStep(A,B,C);
if(tmp<0) puts("No Solution");
else printf("%d\n",tmp);
}
return 0;
}