记录一个菜逼的成长。。
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
求模素数
p
p
p原根的方法:对
p
−
1
p-1
p−1素因子分解,即
p
−
1
=
p
1
a
1
∗
p
2
a
2
∗
⋯
∗
p
k
a
k
p-1 = p_1^{a_1}*p_2^{a_2}* \cdots*p_k^{a_k}
p−1=p1a1∗p2a2∗⋯∗pkak是p-1的标准分解式,若恒有
g
p
−
1
p
i
≠
1
(
m
o
d
p
)
g^{\frac{p-1}{p_i}}\neq1(mod p)
gpip−1=1(modp)
成立,则就是的原根。(对于合数求原根,只需把换成即可)
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <deque>
#include <cctype>
#include <bitset>
#include <cmath>
#include <cassert>
using namespace std;
#define ALL(v) (v).begin(),(v).end()
#define cl(a,b) memset(a,b,sizeof(a))
#define bp __builtin_popcount
#define pb push_back
#define mp make_pair
#define fin freopen("D://in.txt","r",stdin)
#define fout freopen("D://out.txt","w",stdout)
#define lson t<<1,l,mid
#define rson t<<1|1,mid+1,r
#define seglen (node[t].r-node[t].l+1)
#define pi 3.1415926
#define exp 2.718281828459
#define lowbit(x) (x)&(-x)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
typedef vector<PII> VPII;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
template <typename T>
inline void read(T &x){
T ans=0;
char last=' ',ch=getchar();
while(ch<'0' || ch>'9')last=ch,ch=getchar();
while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
if(last=='-')ans=-ans;
x = ans;
}
const int maxn = 1000000 + 10;
bool prime[maxn];
int p[maxn],pri[maxn];
int cnt1,cnt2;
void Iprime()
{
cl(prime,false);
cnt1 = 0;
for( int i = 2; i < maxn; i++ ){
if(!prime[i]){
p[cnt1++] = i;
for( LL j = (LL)i*i; j < maxn; j += i ){
prime[j] = true;
}
}
}
}
void Divide(int num)
{
cnt2 = 0;
int k = sqrt(num);
for( int i = 0; p[i] <= k; i++ ){
if(num % p[i] == 0){
pri[cnt2++] = p[i];
while(num%p[i] == 0)num /= p[i];
}
}
}
LL PowerMod(LL a, LL b, LL c)
{
LL ans = 1;
a = a % c;
while(b>0)
{
if(b % 2 == 1)
ans = (ans * a) % c;
b = b/2;
a = (a * a) % c;
}
return ans;
}
int main()
{
int p;
Iprime();
while(~scanf("%d",&p)){
Divide(p-1);
int ans;
for( int i = 2; i < p; i++ ){
bool flag = true;
for( int j = 0; j < cnt2; j++ ){
int tmp = (p-1)/pri[j];
if(PowerMod(i,tmp,p) == 1){
flag = false;
break;
}
}
if(flag){
ans = i;
break;
}
}
printf("%d\n",ans);
}
return 0;
}