Link: http://poj.org/problem? Id = 2417
Question:
Idea: Evaluate the discrete logarithm. The basic application of the baby step giant step algorithm.
Reposted from: aekdycoin
[Normal baby step giant step]
[Problem model]
Solution
0 <= x <C in a ^ x = B (mod C), where C is a prime number.
[Idea]
We can make an equivalent
X = I * m + J (0 <= I <m, 0 <= j <m) M = Ceil (SQRT (c ))
The purpose of such decomposition is nothing more than to convert:
(A ^ I) ^ M * A ^ J = B (mod C)
Then you can solve the problem by doing a little violent work:
(1) for I = 0-> M, insert Hash (I, a ^ I mod C)
(2) Enumeration I. For each enumerated I, make AA = (a ^ m) ^ I mod C
We have
AA * a ^ J = B (mod C)
Obviously, AA, B, and C are all known. Since C is a prime number, (AA, c) is unconditionally 1.
Therefore, the number of solutions to this model equation is unique (it can be solved by extending Euclidean or Euler's theorem)
Then, find the unique solution X in the hash table. If it is found, return the I * m + J
Note: Due to I enumeration from small to large, the existence of J in the hash table must be the smallest element x in a residual system (that is, the indicator)
Therefore, we can obtain the explain solution at this time.
If you want to obtain a solution of x> 0, you only need to judge in the preceding step that the return value is when I * m + j> 0.
(Reprinted)
This question is only the most basic application, and the complexity is
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <map>#include <cstdlib>#include <queue>#include <stack>#include <vector>#include <ctype.h>#include <algorithm>#include <string>#include <set>#define PI acos(-1.0)#define maxn 10005#define INF 0x7fffffff#define eps 1e-8typedef long long LL;typedef unsigned long long ULL;using namespace std;LL pow_mod(LL aa,LL ii,LL nn){ if(ii==0) return 1%nn; LL temp=pow_mod(aa,ii>>1,nn); temp=temp*temp%nn; if(ii&1) temp=temp*aa%nn; return temp;}struct b_step{ int i,m;} bb[100005];bool cmp(b_step a,b_step b){ return a.m==b.m?a.i<b.i:a.m<b.m;}int BiSearch(int m,LL num){ int low=0,high=m,mid; while(low<=high) { mid=(low+high)>>1; if(bb[mid].m==num) return bb[mid].i; if(bb[mid].m<num) low=mid+1; else high=mid-1; } return -1;}void giant_step_baby_step(LL b,LL n,LL p){ int m=(int)ceil(sqrt((double)p)); bb[0].i=0,bb[0].m=1; for(int i=1; i<m; i++) { bb[i].i=i; bb[i].m=bb[i-1].m*b%p; } sort(bb,bb+m,cmp); int top=0; for(int i=1; i<m; i++) if(bb[i].m!=bb[top].m) bb[++top]=bb[i]; LL bm=pow_mod(pow_mod(b,p-2,p),m,p); LL ans=-1; LL tmp=n; for(int i=0; i<m; i++) { int pos=BiSearch(top,tmp); if(~pos) { ans=m*i+pos; break; } tmp=((LL)tmp*bm)%p; } if(!~ans) puts("no solution"); else printf("%d\n",ans);}int main(){ LL p,b,n; while(~scanf("%lld%lld%lld",&p,&b,&n)) { giant_step_baby_step(b,n,p); } return 0;}