poj1284 - 原根+歐拉函數

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]);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章