51 Nod 1135 原根

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
设m是正整数,a是整数,若a模m的阶等于φ(m),则称a为模m的一个原根。(其中φ(m)表示m的欧拉函数)
给出1个质数P,找出P最小的原根。
Input
输入1个质数P(3 <= P <= 10^9)
Output
输出P最小的原根。
Input示例
3
Output示例
2

/*
求素数的最小原根.
由定理a^i==1(mod)时(i<p) 
当且仅当i==p-1 成立 则a为p的原根.
把p-1质因数分解,然后每次检验(p-1)/pi.
复杂度看起来好像有点高,
但是还是呲呲的2333
(毕竟原根比较多,so......
如果p不是素数的话,把p-1换成phi(p)即可.
*/
#include<iostream>
#include<cmath>
#define MAXN 100001
#define LL long long
using namespace std;
int a[MAXN],tot,ans,p;
void pre()
{
    int tmpp=p-1;
    for(int i=2;i<=sqrt(tmpp);i++)
    {
        if(tmpp%i==0)
        {
            while(tmpp%i==0) tmpp/=i;
            a[++tot]=i;
        }
        if(tmpp==1) break;
    }
    if(tmpp>1) a[++tot]=tmpp;
}
int mi(LL a,int b)
{
    LL tot=1;
    while(b)
    {
        if(b&1) tot=tot*a%p;
        a=a*a%p;
        b>>=1;
    }
    return tot;
}
bool check(int x)
{
    for(int i=1;i<=tot;i++)
      if(mi(x,(p-1)/a[i])==1) return false;
    return true;
}
void slove()
{
    for(int i=2;i<p;i++)
      if(check(i)){ans=i;break;}
}
int main()
{
    cin>>p;
    pre();slove();
    cout<<ans;
    return 0;
}
原文地址:https://www.cnblogs.com/nancheng58/p/10067985.html