原根与指标QAQ。
我们要求的是
xk=a(modp)
,给定
p,k,a,
求解
x
具体做法是给两边同时取
底数为原根
g
则有
然后可以BSGS求出
logga
Exgcd就可以解出
loggx
的所有解。然后快速幂一下即可
注意
logga
一定要整除gcd(k, p-1),否则无解
特判a=0的情况。
xA≡B(modC)
Alnx≡lnB(modφ(C))
判定一个数是否为原根。
对于模数
p,p−1=∏paii
对于任意的
pi
都有
gp−1pimodp
不等于1
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <map>
#define maxn 1000010
using namespace std;
typedef long long ll;
ll p, k, a, g;
//g原根, g^x = a
ll P[maxn], cnt;
void pre_prime(){
ll now = p - 1;
for(ll i = 2; i * i <= now; i ++){
while(now % i == 0){
now /= i;
if(P[cnt] != i)
P[++ cnt] = i;
}
}
if(now != 1) P[++ cnt] = now;
sort(P + 1, P + 1 + cnt);
cnt = unique(P + 1, P + 1 + cnt) - P - 1;
}
ll power_mod(ll a, ll b, ll md){
ll ret = 1;
while(b > 0){
if(b & 1) ret = ret * a % md;
b >>= 1;
a = a * a % md;
}return ret;
}
bool check(){
for(int i = 1; i <= cnt; i ++)
if(power_mod(g, (p - 1) / P[i], p) == 1)
return false;
return true;
}
void find_g(){
for(g = 2; ; g ++)
if(check())return;
}
map<ll, int> M;
ll BSGS(){
if(a == 1)return 0;
ll q = sqrt(p) + 1, now = 1;
M[1] = 1;
for(int i = 1; i <= q; i ++){
now = now * g % p;
if(now == a)return i;
M[now] = i + 1;
}
ll inv = power_mod(now, p - 2, p), attempt = a;
for(int i = 1; i <= q; i ++){
attempt = attempt * inv % p;
if(M.count(attempt))
return M[attempt] - 1 + i * q;
}return -1;
}
void Exgcd(ll a, ll b, ll& d, ll& x, ll& y){
if(!b){d = a, x = 1, y = 0; return;}
Exgcd(b, a%b, d, y, x); y -= x * (a / b);
}
ll ans[maxn];
int main(){
scanf("%lld%lld%lld", &p, &k, &a);
if(a == 0)return puts("1\n0"), 0;
pre_prime();
find_g();
a = BSGS();//find ind_a
ll gcd, x, y;
Exgcd(k, p - 1, gcd, x, y);
if(a % gcd)return puts("0"), 0;
ll b = (p - 1) / gcd;
while(x < 0) x += b;
x = x * a / gcd % b;
int amt = 0;
for(; x < p - 1; x += b)
ans[++ amt] = power_mod(g, x, p);
sort(ans+1, ans+1+amt);
printf("%d\n", amt);
for(int i = 1; i <= amt; i ++)
printf("%lld\n", ans[i]);
return 0;
}