给定
a
,
p
,
b
a,p,b
a,p,b,求
a
x
≡
b
(
m
o
d
p
)
a^x\equiv b \pmod p
ax≡b(modp)的最小自然数
x
x
x .
保证
∑
p
≤
5
×
1
0
6
\sum \sqrt p \leq5\times 10^6
∑p≤5×106
当
a
=
p
=
b
=
0
a=p=b=0
a=p=b=0时,表示输入数据完成。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
typedef long long LL;
const int Hsh=10007;
LL ans,a,p,b,flg[Hsh+5];
vector<pair<LL,int> > V[Hsh+5];
LL Gcd(LL a,LL b){
if(a%b==0) return b;
return Gcd(b,a%b);
}
LL exbsgs(){
memset(flg,0,sizeof(flg));
if(!p) return -1;
if(p==1){
if(!b) return 0;
return -1;
}
if(b==1) return 0;
a%=p;b%=p;
LL g=1,cnt=0,tmpb=1;
while ((g=Gcd(a,p))>1){
if(tmpb%p==b%p) return cnt;
if(b%g) return -1;
b/=g;p/=g;
tmpb=tmpb*(a/g)%p;
cnt++;
}
LL m=ceil(sqrt(double(p)));
LL tmp=1,tmpid=0;
for(int i=1;i<=m;i++){
tmp=tmp*a%p;
tmpid=(tmp*b%p)%Hsh;
if(!flg[tmpid]){
V[tmpid].clear();
flg[tmpid]=1;
}
V[tmpid].push_back(make_pair(tmp*b%p,i));
}
LL res=tmpb%p,tmpres=1;
for(int i=1;i<=m;i++){
res=res*tmp%p;
tmpres=res%Hsh;
if(flg[tmpres]){
for(int j=V[tmpres].size()-1;j>=0;j--){
if(V[tmpres][j].first==res) return (i*m-V[tmpres][j].second)+cnt;
}
}
}
return -1;
}
int main(){
while (scanf("%lld%lld%lld",&a,&p,&b)&&(a|p|b)!=0){
ans=exbsgs();
if(ans==-1) puts("No Solution");
else printf("%lld\n",ans);
}
return 0;
}