BSGS

· · 个人记录

浅谈 \tt BSGS

普通 \tt BSGS

模板题

已知 \tt b , p , l 的值 (\tt p 是质数),求 \tt l 满足 \tt b^l \equiv n \pmod p 的最小非负整数值

由费马小定理得 \tt b ^ l \equiv b ^{l + (p - 1)} , 为了让 \tt l 最小,需要舍掉 \tt l + (p - 1) , 因此 \tt l 的取值范围是 \tt [0,p-2]

如果直接枚举,时间复杂度是 \tt O(p) 的,显然不行

考虑到分块,设块的大小是 \tt B

如果 l 可以表示成 \tt xB-y

那么有:

\tt b ^ {xB - y} \equiv n \pmod p \tt b ^ {xB} \ b^{-y} \equiv n \pmod p \tt b ^ {xB} \equiv n \ b^y \pmod p

首先预处理出 \tt b^B,b^{2B},b^{3B} ... b^{B^2}的值,存进 map 里

之后枚举 \tt b^1,b^2,b^3...b^{B} 得到 \tt n \ b^y 的值,从而得出 \tt b ^ {xB} 中 \tt x 的值,就计算出了最小的 \tt l

丑陋的代码:

#include<bits/stdc++.h>
using namespace std;
map<long long,long long> ma;
long long n,b,mod,kuai,now,gg;
int main() {
    scanf("%lld%lld%lld",&mod,&b,&n);
    kuai = sqrt(mod) , now = n % mod;
    for(int i = 0; i < kuai; i++) ma[now] = i , now = now * b % mod;
    now = 1,gg = 1;
    for(int i = 1; i <= kuai; i++) now = now * b % mod;
    for(int i = 1; i <= kuai; i++) {
        gg = gg * now % mod;
        if(ma[gg]) return printf("%lld\n",i*kuai-ma[gg]),0; 
    }
    return printf("no solution"),0;
} 

拓展 \tt BSGS

模板题

已知 \tt b , p , l 的值 ,求 \tt l 满足 \tt b^l \equiv n \pmod p 的最小非负整数值

这时候 \tt b 与 \tt p 不一定互质了,所以要用拓展 \tt BSGS

设 \tt x 为 \tt \gcd (p,b)

只要有解,则 n \equiv 0 \pmod x

\tt b \ \ b ^ {l-1}\equiv n \pmod p \tt \frac{b}{x} b ^ {l-1} \equiv \frac{n}{x} \pmod {\frac{p}{x}} \tt b ^ {l-1} \equiv \frac {\frac{n}{x}}{\frac{b}{x}} \pmod {\frac{p}{x}}

然后继续递归即可。出现了 \tt \gcd(a,p) = 1 时就停止递归,跑一遍普通 \tt BSGS 就行了

Code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
void exgcd(ll a,ll b,ll &x,ll &y) {
    if(b == 0) return (void)(x = 1, y = 0);
    ll t = a/b;
    exgcd(b,a-b*t,y,x) , y = y - t * x;
}
ll ny(ll aa,ll mod) {
    ll sa,sb;
    exgcd(aa,mod,sa,sb);
    return (sa%mod+mod)%mod;
}
unordered_map<ll,ll> ma;
ll n,b,mod,kuai,now,gg,yy,sans,cc;
void BSGS() {
    scanf("%lld%lld%lld",&b,&mod,&n),sans=0,cc=1;
    if(!mod&&!b&&!n) return;
    if(b == 1 || mod == 1) return (printf("0\n"),ma.clear(),BSGS());
    while((yy=__gcd(mod,b)) > 1) {
        if(n%yy) return (printf("No Solution\n"),ma.clear(),BSGS());
        ++sans,mod/=yy,n/=yy,cc=cc*(b/yy)%mod;
        if(cc == n) return (printf("No Solution\n"),ma.clear(),BSGS());
    }
    n = n * ny(cc,mod) % mod;
    kuai = sqrt(mod) , now = n;
    for(int i = 0; i < kuai; i++) ma[now] = i , now = now * b % mod;
    now = 1,gg = 1;
    for(int i = 1; i <= kuai; i++) now = now * b % mod;
    for(int i = 1; i <= kuai; i++) {
        gg = gg * now % mod;
        if(ma[gg]) return (printf("%lld\n",i*kuai-ma[gg]+sans),ma.clear(),BSGS()); 
    }
    return (printf("No Solution\n"),ma.clear(),BSGS());
}
int main() {
    BSGS();
    return 0;
}