BSGS算法,预处理出ϕ(c)−−−−√内的a的幂,每次再一块一块的往上找,转移时将b乘上逆元,哈希表里O(1)查询即可
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<map>
#define LL long long
long long a,b,c,m;
bool bo=0;
std::map<long long,int> pp;
std::map<long long,bool> vis;
LL exgcd(LL o,LL p,LL &x,LL &y){
if(p==0){
x=1;y=0;
return o;
}
LL gcd=exgcd(p,o%p,x,y);
LL t=x;
x=y;
y=t-(o/p)*x;
return gcd;
}
int main(){
while(scanf("%lld%lld%lld",&c,&a,&b)==3){
pp.clear(); vis.clear(); bo=0;
if(a%c==0){printf("no solution\n");continue;}
m=(LL)ceil(sqrt((double)c));
LL now=1;
pp[now]=0; vis[now]=1;
for(int i=1;i<m;i++){
now=(now*a)%c;
if(!vis[now]){vis[now]=1;pp[now]=i;}
}
now=(now*a)%c;
LL x,y;
LL d=exgcd(now,c,x,y);
x=(x%c+c)%c;
for(int i=0;i<=m;i++){
if(vis[b]){
printf("%lld\n",i*m+pp[b]);
bo=1; break;
}
b=(b*x)%c;
}
if(bo==1)continue;
printf("no solution\n");
}
return 0;
}