BSGS & ExBSGS study notes

BSGS&ExBSGS

Solving the form

\[a^x\equiv b\pmod p\]

The high-order congruence equation

BSGS

Pretending \ (GCD (A, P) =. 1 \) .

Set \ (m = \ lceil \ sqrt p \ rceil \)

Then \ (X \) is decomposed into

\[x=i*m+j\]

form.

\ [A ^ X \ equiv B \ PMOD P \]
\ [A ^ {I * m + J} \ equiv B \ PMOD P \]
\ [A ^ {IM} \ equiv B / A ^ J \ PMOD P \ ]
At this time we have found, \ (1≤j≤m-1 \) , that is to enumerate \ (j \) is very simple.

So that we can put \ (m-1 \) a \ (J \) are all stored together, to keep the hash table, and then enumerate \ (I \) , so that you can \ (O (\ sqrt n + log (n)) \) is obtained in the solution of the time. (Block + map)

(Time complexity is wyh find online, they will not permit qwq

ExBSGS

We just pretend \ (gcd (A, the p-) = 1 \) , and that this condition if not how to do it?

Quite simply, we just divide their gcd thousand million at the same time by both sides of the qwq

Set \ (G = gcd (A, the p-) \) , if \ (G \ not | b \) , obviously if \ (p = 1 \) is \ (the X-= 0 \) , otherwise the equation has no solution

We get

\[a^{x-1}*\frac{a}{g}\equiv \frac{b}{g}\pmod {\frac{p}{g}}\]
\[a^{x-1}\equiv \frac{b}{a}\pmod \frac{p}{g}\]

Such has been doing this until \ (g = 1 \) so far.

There is a misunderstanding (for me that konjac) is \ (a \) and \ (b / g \) is not necessarily relatively prime. This is zzy seniors tell wyh of qwq, or seniors Well qwq.

I am deeply moved ah. . .

Code


typedef long long ll;
map<ll,ll> ma;
inline ll bsgs(ll a,ll b)//解a^x同余b (%mod) 
{
    a%=mod;b%=mod;
    ma.clear();
    ll m=ll(sqrt(mod+1)),e=1;
    for(int j=0;j<m;++j)
    {
        if(!ma.count(e)) ma[e]=j;
        e=e*a%mod;
    }
    if(gcd(e,mod)!=1) return -1;
    ll inv=inverse(e);//逆元 
    for(int i=0;i<m;++i)
    {
        if(ma.count(b)) return i*m+ma[b];
        b=b*inv%mod;
    }
    return -1;
}

Guess you like

Origin www.cnblogs.com/oierwyh/p/11375107.html