离散对数问题:给定求y,z,p,y,z,p,求 yx≡zyx≡z (mod(mod p)p)的最小整数解.
BSGS
Shank的大步小步算法(Shank’s Baby-Step-Giant-Step Algorithm)
这里介绍一种避开求逆元的BSGS(常数小
令m=⌈p–√⌉m=⌈p⌉,x=im−jx=im−j
则 yim−j≡zyim−j≡z (mod(mod p)p)
两边同乘yjyj得:
yim≡zyjyim≡zyj (mod(mod p)p)
mm、、zz已知,因此先枚举右边.算出来的值放进map里。再接着枚举左边,yim,i∈[1,m]yim,i∈[1,m],如果发现map里有与之对应的值,返回im−jim−j,即要求xx.最后若未返回则无解.
(可以看出BSGS是确定了枚举上界的暴力枚举算法.
LL Qpow(LL a, LL b) {
LL ans = 1LL;
for(; b; b >>= 1, a = a * a % p)
if(b & 1) ans = ans * a % p;
return ans;
}
LL BSGS(LL y, LL z) {
map<int, int> M;
LL m = ceil(sqrt(p + 0.5)), cj = z;
for(int j = 0; j < m; j++) {
M[cj] = j;
cj = cj * y % p;
}
LL now = Qpow(y, m);
cj = 1;
for(int i = 1; i <= m; i ++) {
cj = cj * now % p;
if(M.count(cj)) return i*m - M[cj];
}
return -1;
}
Extended BSGS
待更。