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
基本上参考了大神-ACdreamers的代码:http://blog.csdn.net/acdreamers/article/details/8883285
素数筛选法筛选素数,p-1的标准分解式的方法来验证是否为原根,最后用快速幂取模来优化
#include <iostream>
#include <math.h>#include <string.h>
using namespace std;
const int N=1000010;
int a[N],p,b[N],c[N];
long long quckmod(long long x,long long y,long long z)
{
x%=z;
long long sum=1;
while(y)
{
if(y&1)
{
y--;
sum=(sum*x)%z;
}
y>>=1;
x=(x*x)%z;
}
return sum;
}
int main()
{ int i,y,l=0,n,pt,j;
for(i=0;i<N;i++)
a[i]=1;
for(i=2;i<N;i++)
if(a[i])
{ b[l]=i;l++;
for(j=i+i;j<N;j+=i)
a[j]=0;
}
while(cin>>p)
{ pt=p-1; n=0;
for(i=0;b[i]*b[i]<=p-1;i++)
{
if(pt%b[i]==0)
{ c[n]=b[i];
n++;
while(pt%b[i]==0)
{
pt/=b[i];
}
}
}
if(pt>1) {c[n]=pt;n++;}
for(i=2;i<p;i++)
{ for(j=0;j<n;j++)
{
if(quckmod(i,(p-1)/c[j],p)==1) break;
}
if(j==n) {y=i;break;}
}
cout<<y<<endl;
}
return 0;
}