51nod 1135 原根

本文介绍了一种用于寻找整数p的原根的有效算法。通过分解p-1的质因数,并利用快速幂运算,该算法能高效地判断一个数是否为原根。文中提供了完整的C++代码实现。

传送门

题目

//Achen
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<vector>
#include<queue>
#include<ctime>
#include<cmath> 
typedef long long LL;
using namespace std;
int p,d[100],mod;

template<typename T> void read(T &x) {
    char ch=getchar(); x=0; T f=1;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') f=-1,ch=getchar();
    for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0'; x*=f;
}

LL ksm(LL a,LL b) {
    LL base=a,res=1;
    while(b) {
        if(b&1) (res*=base)%=mod;
        (base*=base)%=mod;
        b>>=1;
    }
    return res;
}

int main() {
#ifdef DEBUG
    freopen(".in","r",stdin);
    freopen(".out","w",stdout);
#endif
    read(p); 
    mod=p; p--;
    int nn=sqrt(p),tp=p;
    for(int i=2;i<=nn;i++) 
        if(tp%i==0) {
            d[++d[0]]=i;
            while(tp%i) 
                tp/=i;
        }
    if(tp!=1) d[++d[0]]=tp;
    for(int i=2;i<=p;i++) {
        int fl=1;     
        for(int j=1;j<=d[0];j++) {
            if(ksm(i,p/d[j])==1) {
                fl=0;
                break;
            }
        }
        if(fl) {
            printf("%d\n",i); 
            break;
        }
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/Achenchen/p/8079110.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值