[BZOJ 1420 && BZOJ 1319]

来源:互联网 发布:黑客帝国3矩阵革命免费 编辑:程序博客网 时间:2024/06/07 04:46

原根与指标QAQ。
我们要求的是xk=a(modp),给定pka求解x
具体做法是给两边同时取log
底数为原根g
则有kloggx=logga(modp)
然后可以BSGS求出logga
Exgcd就可以解出loggx的所有解。然后快速幂一下即可
注意logga一定要整除gcd(k, p-1),否则无解
特判a=0的情况。
xAB(modC)
AlnxlnB(modφ(C))

判定一个数是否为原根。
对于模数pp1=paii
对于任意的pi都有gp1pimodp不等于1

#include <algorithm>#include <iostream>#include <cstring>#include <cstdio>#include <vector>#include <cmath>#include <map>#define maxn 1000010using namespace std;typedef long long ll;ll p, k, a, g;//g原根, g^x = all 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;}
0 0
原创粉丝点击