Baby_Step_Giant_Step
//求解的是a^x = b(mod c)的最小x解
struct node {
int num;
int val;
} baby[maxn];
bool cmp(node a, node b) {
if (a.val != b.val) return a.val < b.val;
return a.num < b.num;
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int Ex_gcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
int ans = Ex_gcd(b, a % b, x, y);
int temp = x;
x = y;
y = temp - a / b * y;
return ans;
}
int inval(int a, int b, int n) {
int re, x, y;
Ex_gcd(a, n, x, y);
re = ((LLI)x * b) % n;
return re < 0 ? (re + n) : re;
}
LLI Fast_power(LLI n, LLI k, LLI mod) {
if (k == 0) return 1;
LLI temp = Fast_power(n, k / 2, mod);
temp = (temp * temp) % mod;
if (k % 2 == 1) temp = (temp * (n % mod)) % mod;
return temp;
}
int BinSearch(int n, int m) {
int Lef = 0, Rig = m - 1, mid;
while (Lef <= Rig) {
mid = (Lef + Rig) >> 1;
if (baby[mid].val == n) return baby[mid].num;
if (baby[mid].val < n) Lef = mid + 1;
else Rig = mid - 1;
}
return -1;
}
int BabyStep(int a, int b, int c) {
LLI p, d = 1 % c, temp, pd = 0;
for (int i = 0, p = 1 % c; i < 100; i++, p = ((LLI)p * a) % c)
if (p == b) return i;
while ((temp = gcd(a, c)) != 1) {
if (b % temp) return -1;
pd++;
c /= temp;
b /= temp;
d = a / temp * d % c;
}
int m = (int)ceil(sqrt((double)c));
for (int i = 0, p = 1 % c; i <= m; i++, p = ((LLI)p * a) % c) {
baby[i].num = i;
baby[i].val = p;
}
sort(baby, baby + m + 1, cmp);
int cnt = 1;
for (int i = 1; i <= m; i++) {
if (baby[i].val != baby[cnt - 1].val)
baby[cnt++] = baby[i];
}
int am = Fast_power(a, m, c);
for (int i = 0; i < m; i++, d = ((LLI)(d * am)) % c) {
p = inval(d, b, c);
if (p >= 0) {
int pos = BinSearch(p, cnt);
if (pos != -1) return i * m + pos + pd;
}
}
return -1;
}