#include<iostream> #include<cstdio> #include<cmath> #include<map> #define LL long long using namespace std; LL p,b,n; LL poww(LL a,LL b,LL p) { LL ans=1; while(b) { if(b&1)ans=ans*a%p; a=a*a%p; b=b>>1; } return years; } LL bsgs(LL a,LL b,LL p) { map<LL,LL>mp;mp.clear(); LL m=ceil(sqrt(p*1.0)); for(int j=0;j<=m;j++) { LL val=b*poww(a,j,p)%p; Mp [Val] = J; } a=poww(a,m,p); if(!a)return !b?0:-1; for(int i=0;i<=m;i++) { LL val=poww(a,i,p); LL j=mp.find(val)==mp.end()?-1:mp[val]; if(j>=0 && i*m-j>=0)return i*m-j; } return -1; } signed main() { while(cin>>p>>b>>n) { LL ans=bsgs(b,n,p); if(ans==-1)puts("no solution"); else cout<<ans<<endl; } }
With Hash will be faster, map will be multiple log.
ax≡b (mod p)
So that x = i * mj, where m = ceil (sqrt (p));
a i * mj ≡b (mod p)
to i * m ≡b * a j (mod p)
Enumeration J (0 <= J <= m), Map [A B * J ] = J,
If a = 0, b! = 0, no solution, a = 0, b = 0, then x = 0;
Enumeration i (1 <= i <= m), to find the first i, so that A I * m ≡ B * A J (P MOD) established, i * mj is also desired.