poj 2417(BSGS)

poj 2417

BSGS模板题,见此处

#include<cstdio> 
#include<cstring>
#include<algorithm>
#include<map>
#include<cmath>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
LL p, x, z;
map<LL, LL> a;
LL ksm(LL a, LL b, LL m) {
    LL base = a, ret = 1;
    while (b) {
        if (b & 1) ret = (ret * base) % m;
        b >>= 1, base = (base * base) % m;
    }
    return ret;
}
void clean() {
    a.clear();
}
int solve() {
    clean(); 
    LL m = (LL)ceil(sqrt(p - 1)), whw = x;//必须ceil取大,否则会小
    a[1] = m + 1;
    for (LL i = 1; i < m; i++) {//求左边的x^b
        if (!a.count(whw)) a[whw] = i;
        whw = (whw * x) % p;
    }
    LL ni = ksm(x, m, p); ni = ksm(ni, p - 2, p);//x^{-m}
    for (LL i = 0; i < m; i++) {//枚举a
        LL j = a[z];
        if (j) {
            if (j == m + 1) return printf("%lld\n", i * m), 0; else return printf("%lld\n", i * m + j), 0;
        }
        z = (z * ni) % p;
    }
    printf("no solution\n");
    return 0;
}
int main() {
    while (scanf("%lld%lld%lld", &p, &x, &z) == 3) x %= p, z %= p, solve();
    return 0;
}
------ 本文结束 ------