BSGS study notes

BSGS algorithm

BSGS use algorithms to solve \ (x \) equation
\ [x ^ y \ equiv z
\ pmod p \] where \ (gcd (the X-, the p-) = 1 \) , we \ (y \) written as a \ (am - b \) form, where \ (a \ in (. 1,. 1 + m] \) , \ (B \ in [0, m) \)

So this, the original formula becomes
\ [\ begin {aligned} x ^ {am - b} & \ equiv z \ pmod p \\ x ^ {am} & \ equiv z * x ^ b \ pmod p \ end {aligned} \]
we enumerate each \ (B \) , the \ (z * x ^ b \ ) stored into \ (the hash \) or \ (Map \) and stuff

After left for each enumeration \ (A \) , if \ (x ^ {am} \ % p \) in \ (the hash \) or \ (Map \) , the answer is \ (a * m - mp [x ^ {am} \% p] \)

Complexity \ (O (max (m, P / m)) \) , is easy to prove to obtain \ (m \) of \ (\ sqrt {p} \ ) when optimal

Code

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <cmath>
#include <map>
#define itn int
#define reaD read
using namespace std;

int p, x, y, s, m;
map<int, int> mp; 

inline int read()
{
    int x = 0, w = 1; char c = getchar();
    while(c < '0' || c > '9') { if (c == '-') w = -1; c = getchar(); }
    while(c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * w;
}

int fpow(int x, int k)
{
    int res = 1;
    while(k)
    {
        if(k & 1) res = 1ll * res * x % p;
        x = 1ll * x * x % p;
        k >>= 1; 
    }
    return res; 
}

int main()
{
    p = reaD(); x = read(); y = read(); m = sqrt(p) + 1; s = y; 
    for(int i = 0; i < m; i++) mp[s] = i, s = 1ll * s * x % p; 
    s = 1; int t = fpow(x, m); 
    for(int i = 1; i <= m + 1; i++)
    {
        s = 1ll * s * t % p; 
        if(mp.count(s))
        {
            printf("%d\n", i * m - mp[s]);
            return 0; 
        }
    }
    puts("no solution"); 
    return 0;
}

ExBSGS algorithm

If all have \ (Ex \) algorithm seems eh without co-prime

Here, \ (ExBSGS \) is used to handle \ (gcd (x, p) ! = 1 \) case, we can have such a formula, set \ (GCD (X, P) = D \)
\ [<Empty \ space Math \ space Block> \]

Guess you like

Origin www.cnblogs.com/ztlztl/p/11024724.html