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
| ll bsgs(ll y, ll z, ll p) { map< ll, ll > M; ll m = sqrt(p) + 1; y %= p; z %= p;
ll cnt = 0, sum = 1; for (int d = gcd(y, p); d != 1; d = gcd(y, p)) { if (z % d) return -LLONG_MAX; ++cnt, z /= d, p /= d, sum = sum * y / d % p; if (z == sum) return cnt; }
for (ll i = 0, zy_i = z; i <= m; i++, zy_i = zy_i * y % p) M[zy_i] = i;
for (ll i = 1, y_m = fastPower(y, m, p), y_mi = y_m; i <= m; i++, y_mi = y_mi * y_m % p) if (M.count(y_mi)) return i * m - M[y_mi];
return -LLONG_MAX; }
|