码迷,mamicode.com
首页 > 其他好文 > 详细

快速求原根

时间:2018-06-23 22:50:49      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:ring   lag   char   html   problem   rac   work   long   break   

当需要求质数\(P\)的原根\(G\),只需枚举\(a \in [2,P - 1]\),检验对\(P - 1\)的所有质因子\(p_i\)\(a^{\frac{P - 1}{p_I}} \mod P\)是否等于\(0\),若都不等于\(0\),则\(a\)\(P\)的原根

51Nod原根

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 1000000000;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57){if (c == ‘-‘) flag = -1; c = getchar();}
    while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
    return out * flag;
}
inline int qpow(int a,LL b,int pr){
    int re = 1;
    for (; b; b >>= 1,a = 1ll * a * a % pr)
        if (b & 1) re = 1ll * re * a % pr;
    return re;
}
int P,fac[maxn],cnt;
void Sp(int x){
    for (int i = 2; i * i <= x; i++)
        if (x % i == 0){
            fac[++cnt] = i;
            while (x % i == 0) x /= i;
        }
    if (x - 1) fac[++cnt] = x;
}
void work(){
    for (int i = 2; i < P; i++){
        int flag = true;
        for (int j = 1; j <= cnt; j++)
            if (qpow(i,(P - 1) / fac[j],P) == 1){
                flag = false;
                break;
            }
        if (flag){
            printf("%d\n",i);
            break;
        }
    }
}
int main(){
    P = read();
    Sp(P - 1);
    work();
    return 0;
}

快速求原根

标签:ring   lag   char   html   problem   rac   work   long   break   

原文地址:https://www.cnblogs.com/Mychael/p/9218871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!