此题是个板子题EXBSGS算法
用到费马小定理推出的算法
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> pLL;
typedef pair<LL, int> pli;
typedef pair<int, LL> pil;;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define lson i<<1
#define rson i<<1|1
#define lowbit(x) x&(-x)//lowbit(x)是x的二进制表达式中最低位的1所对应的值。
const double eps = 1e-8;
const int mod = 1e9 + 7;
const int maxn = 1e6 + 7;
const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
int t, a, b, m;
unordered_map<LL, int> mp;
LL Mod_Pow(LL x, LL n, LL mod) {
LL res = 1;
while(n) {
if(n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
LL EXBSGS(int A, int B, int C) {
A %= C, B %= C;
if(B == 1) return 0;
int cnt = 0;
LL t = 1;
for(int g = gcd(A, C); g != 1; g = gcd(A, C)) {
if(B % g) return -1;
C /= g, B /= g;
t = t * A / g % C;
cnt++;
if(B == t) return cnt;
}
mp.clear();
int m = ceil(sqrt(1.0 * C));
LL base = B;
for(int i = 0; i < m; i++) {
mp[base] = i;
base = base * A % C;
}
base = Mod_Pow(A, m, C);
LL nw = t;
for(int i = 1; i <= m + 1; i++) {
nw = base * nw % C;
if(mp.count(nw)) {
return i * m - mp[nw] + cnt;
}
}
return -1;
}
int main() {
scanf("%d", &t);
while(t--) {
scanf("%d%d%d", &a, &b, &m);
LL ans = EXBSGS(a, b, m);
printf("%lld\n", ans);
}
return 0;
}