BSGS(Baby steps giant steps)算法学习笔记
离散对数(Discrete Logarithm)问题是这样一个问题,它是对于模方程
a^x=b(mod prime),求满足条件的X,或者得出不存在这样的X
最暴力的思路,那么就是枚举x? 根据费马小定理,只需要枚举[0,p-1)
但是还是很大…我们不禁想到把x写成x=A*m+B的形式,m=ceil(sqrt(p))
因此有
,变形得到

然后预处理一边存到map中,从小到大枚举另一边看是否存在…
我们可以设
,其中
,
,这样的话化简后的方程就是

就可以不用求出逆元,要注意只是不用求出逆元,而不是没有用到逆元的存在
就可以不用求出逆元,要注意只是不用求出逆元,而不是没有用到逆元的存在
就可以不用求出逆元,要注意只是不用求出逆元,而不是没有用到逆元的存在
其实在m=sqrt(p)的时候你可能就有预感了…
BSGS算法的本质,就是个分块啊,而分块的本质就是暴力乱搞…所以BSGS看起来很高大上的算法不过是暴力乱搞2333
而BSGS的名字也很贴切…A的变化是giant step?B的变化是baby step? (纯属yy…但是我感觉这样想很好理解啊?
需要注意的是,这里介绍的是常规的BSGS算法,
前提条件是a和P互质
前提条件是a和P互质
前提条件是a和P互质
放一个板子好了,poj 2417
1/* ***********************************************
2Author :111qqz
3Created Time :2017年07月23日 星期日 11时11分00秒
4File Name :2417.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define PB push_back
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28
29using namespace std;
30const double eps = 1E-8;
31const int dx4[4]={1,0,0,-1};
32const int dy4[4]={0,-1,1,0};
33const int inf = 0x3f3f3f3f;
34LL p,b,n;
35map<LL,LL>Hash;
36map<LL,LL>::iterator it;
37inline LL ksm(LL a,LL b,LL MOD)
38{
39 LL res = 1LL;
40 while (b)
41 {
42 if (b&1) res = (res*a)%MOD;
43 b = b >> 1;
44 a = (a*a)%MOD;
45 }
46 return res;
47}
48LL BSGS(LL a,LL b ,LL p) // a^x = b (mod p),求x
49{
50 a%=p;
51 b%=p;
52 if (!a&&!b) return 1;
53 if (!a) return -1;
54 Hash.clear();
55 LL m = ceil(sqrt(double(p)));
56 LL tmp = b;
57 for (LL j = 0 ; j <= m ; j++)
58 {
59 Hash[tmp]=j;
60 tmp = (tmp*a)%p;
61 }
62 tmp = ksm(a,m,p);
63 LL ret = 1;
64
65 for (LL i = 1 ; i <= m+1 ; i++)
66 {
67 ret = ret*tmp%p;
68 if (Hash[ret]) return i*m-Hash[ret]; //注意处理下%....虽然其实不处理也没关系...
69 }
70 return -1;
71
72}
73int main()
74{
75 #ifndef ONLINE_JUDGE
76 // freopen("./in.txt","r",stdin);
77 #endif
78 while (~scanf("%lld%lld%lld",&p,&b,&n)) // B^L = n(mod p)
79 {
80 LL ans = BSGS(b,n,p);
81 if (ans==-1) printf("no solution\n");
82 else printf("%lld\n",(ans%p+p)%p);
83 }
84
85
86 #ifndef ONLINE_JUDGE
87 fclose(stdin);
88 #endif
89 return 0;
90}
参考资料: