Primitive Roots
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 6012 | Accepted: 3434 |
Description
We say that integer x, 0 < x < p, is a primitive root modulo odd prime p if and only if the set { (xi mod p) | 1 <= i <= p-1 } is equal to { 1, ..., p-1 }. For example, the consecutive powers of 3 modulo 7 are 3, 2, 6, 4, 5, 1, and thus 3 is a primitive root modulo 7.
Write a program which given any odd prime 3 <= p < 65536 outputs the number of primitive roots modulo p.
Input
Each line of the input contains an odd prime numbers p. Input is terminated by the end-of-file seperator.
Output
For each p, print a single number that gives the number of primitive roots in a single line.
Sample Input
23 31 79
Sample Output
10 8 24
思路:
原根的定义:摘自百度百科
原根是一种数学符号,设m是正整数,a是整数,若a模m的阶等于φ(m),则称a为模m的一个原根。(其中φ(m)表示m的欧拉函数) [1]
假设一个数g是P的原根,那么g^i mod P的结果两两不同,且有 1<g<P,0<i<P,归根到底就是g^(P-1) = 1 (mod P)当且仅当指数为P-1的时候成立.(这里P是素数)。
简单来说,g^i mod p ≠ g^j mod p (p为素数),其中i≠j且i, j介于1至(p-1)之间,则g为p的原根。
求原根目前的做法只能是从2开始枚举,然后暴力判断g^(P-1) = 1 (mod P)是否当且仅当指数为P-1的时候成立。而由于原根一般都不大,所以可以暴力得到。
根据加粗的话,可以看出来题目就是让求原根的个数
另外:阶的定义
对于素质数p:原根个数是φ(φ(p)),又因为p是质数,φ(p)=p-1,所以原根个数为φ(p-1)
对于合数以及2:原根个数为0
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
const int N=65540,mod=10007;
int is_prime[N],euler[N];
void sieve(ll n){//筛素数
is_prime[1]=1;//不是素数
for(ll i=2;i<=n;i++){
if(!is_prime[i]){//是素数
for(ll j=2*i;j<=n;j+=i){
is_prime[j]=1;//不是素数
}
}
}
is_prime[2]=1;
}
void phi(int n){//欧拉函数打表
for(int i=0;i<=n;i++)euler[i]=i;
for(int i=2;i<=n;i++){
if(euler[i]==i){
for(int j=i;j<n;j+=i){
euler[j]=euler[j]/i*(i-1);
}
}
}
}
int main(){
ll p;
sieve(65536);
phi(65536);
while(scanf("%lld",&p)!=EOF){
if(is_prime[p]==1){
printf("0\n");
continue;
}
printf("%d\n",euler[p-1]);
}
}