数论原根 及其求法

来源:互联网 发布:淘宝账号密码破解 编辑:程序博客网 时间:2024/06/05 03:24

原根

原根求法

定义2:若G为n的原根,则当gcd(i,φ(n))==1,Gi也为n的原根
可以通过先求出n的最小原根,来枚举得到其他的合法原根。

#include <algorithm>#include <cstring>#include <cstdio>#define ll long longusing namespace std;const int maxn = 1e6 + 10;bool vis[maxn] = {0};int pri[maxn / 10] = {0};int phi[maxn] = {0};int n,k;int temp[maxn] = {0};int cnt = 0;ll res[maxn] = {0};void init () {    for (int i = 2;i < maxn; ++ i) {        if (!vis[i]) {            pri[cnt ++] = i;            for (int j = i + i;j < maxn;j += i) {                vis[j] = 1;            }        }    }    phi[1] = 1;    memset (vis,0,sizeof (vis));    for (int i = 2;i < maxn; ++ i) {        if (!vis[i]) {            for (int j = i;j < maxn; j += i) {                vis[j] = 1;                if (phi[j] == 0) phi[j] = j;                phi[j] = phi[j] / i * (i - 1);            }        }    }}void div (int n) {    k = 0;    for (int i = 0;pri[i] * pri[i] <= n; ++ i) {        if (n % pri[i] == 0) {            temp[k ++] = pri[i];            while (n % pri[i] == 0) n /= pri[i];        }    }    if (n > 1) temp[k ++] = n;}ll lpow (ll a,ll b,ll m) {    ll ans = 1;    a %= m;    while (b) {        if (b & 1) {            ans = ans * a % m;            b --;        }        b >>= 1;        a = a * a % m;    }    return ans % m;}bool check (int n) {    if (n == 2 || n == 4) return true;    if (n % 2 == 0) n /= 2;    if (binary_search (pri + 1,pri + cnt,n)) return true;    for (int i = 1;i < cnt && pri[i] * pri[i] <= n; ++ i) {        if (n % pri[i] == 0) {            while (n % pri[i] == 0) {                n /= pri[i];            }            if (n == 1)return true;            break;        }    }    return false;}int main () {    init ();    while (scanf ("%d",&n) != EOF) {        if (n == 2) {            printf ("1\n");            continue ;        }        if (check(n) == 0) {            printf ("-1\n");            continue;        }        int tot = 0;        int p = phi[n];        div (p);        for (int q = 2;q < n; ++ q) {            if (__gcd (q,n) != 1) continue;            int flag = 1;            for (int i = 0;i < k; ++ i) {                int t = p / temp[i];                if (lpow(q, t, n) % n == 1) {                    flag = 0;                    break;                }            }            if(flag) {                res[tot ++] = q;                break;            }        }        ll cc = res[0];        tot = 0;        for (int i = 1;i < p; ++ i) {            if (__gcd (i,p) == 1) {                res[tot ++] = cc;            }            cc = cc * res[0] % n;        }        sort (res,res + tot);        if (tot) {            printf ("%lld",res[0]);            for (int i = 1;i < tot; ++ i) {                printf (" %lld",res[i]);            }        }        else {            printf ("-1");        }        printf ("\n");    }    return 0;}
原创粉丝点击