poj 2417(BSGS)

poj 2417

BSGS模板题,见此处

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#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;
}
------ 本文结束 ------