【模板】Big-Step-Giant-Step 大步小步

求一个

g^x$equiv$f(mod~h)的最小整数解

bsgs 当h是质数的时候使用

extbsgs 不满足上面那种情况的时候

具体参见http://tonyfang.is-programmer.com/posts/178997.html

ll gcd(ll a,ll b) {
    return b?gcd(b,a%b):a;
}
ll bsgs(ll A,ll B,ll C) {
    ll m,v,e=1,i;
    m=ceil(sqrt(C));
    map<ll,ll> hash;
    hash[1]=m;
    for (i=1;i<m;++i) {
        e=(e*A)%C;
        if(!hash[e]) hash[e]=i;
    } 
    e=e*A%C;
    e=inverse(e,C);
    for (i=0;i<m;++i) {
        if(hash[B]) {
            ll ret=hash[B];
            hash.clear();
            return i*m+(ret==m?0:ret);
        }
        B=(B*e)%C;
    }
    return -1;
}
ll extbsgs(ll a,ll b,ll c) {
    ll t,d=1,cnt=0; 
    while((t=gcd(a,c))!=1) {
        if(b%t) return -1;
        b/=t, c/=t;
        d=d*a/t%c;
        cnt++;
        if(d==b) return cnt;
    }
    b=b*inverse(d,c)%c;
    ll ret=bsgs(a,b,c);
    if(ret==-1) return -1;
    else return cnt+ret;
}
void q2(){
    //BSGS
    if(!f)
        cout<<-1<<endl;
    else
        cout<<extbsgs(g,f,h)<<endl;
}
原文地址:https://www.cnblogs.com/chouti/p/5814915.html