We say that integer x, 0 < x < p, is a primitive root modulo odd prime p if and only if the set { (x i 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

欧拉函数:对正整数n,欧拉函数是少于或等于n的数中与n互质的数的数目。例如euler(8)=4,因为1,3,5,7均和8互质。
Euler函数表达通式:euler(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…(1-1/pn),其中p1,p2……pn为x的所有素因数,x是不为0的整数。euler(1)=1(唯一和1互质的数就是1本身)。
欧拉公式的延伸:一个数的所有质因子之和是euler(n)*n/2。
欧拉定理:对于互质的正整数a和n,有aφ(n) ≡ 1 mod n。
欧拉函数是积性函数——若m,n互质,φ(mn)=φ(m)φ(n)。
若n是质数p的k次幂,φ(n)=p^k-p^(k-1)=(p-1)p^(k-1),因为除了p的倍数外,其他数都跟n互质。
特殊性质:当n为奇数时,φ(2n)=φ(n)
欧拉函数还有这样的性质:
设a为N的质因数,若(N % a == 0 && (N / a) % a == 0) 则有E(N)=E(N / a) * a;若(N % a == 0 && (N / a) % a != 0) 则有:E(N) = E(N / a) * (a - 1)。
那么如何变成实现欧拉函数呢?下面通过两种不同的方法来实现。第一种方法是直接根据定义来实现,同时第一种方法也是第二种筛法的基础,当好好理解。
可以得到关于欧拉函数的递推关系:
假设素数p能整除n,那么
如果p还能整除n / p, PHI(n) = PHI(n / p) * p;
如果p不能整除n / p, PHI(n) = PHI(n / p) * (p - 1);

#include <iostream>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<cmath>
#define Max 1000001
#define ll long long
using namespace std;
//欧拉函数方法一:线性时间打表,但此时φ(p)=p-1
//方法二:直接求解欧拉函数
int euler1(int n)
{
    int res = n, a = n;
    for(int i=2; i<=sqrt(n);i++)
    {
        if(a%i==0)
        {
            res = res/i*(i-1);//先进行除法是为了防止中间数据的溢出
            while(a%i==0) a/=i;
        }
    }
    if(a>1) res = res/a*(a-1);
    return res;
}
int euler[Max];
// O(MAX_N)时间筛出欧拉函数值的表
void iii()
{
	for (int i = 0; i < Max; ++i) euler[i] = i;
	for (int i = 2; i < Max; ++i)
	{
		if (euler[i] == i)
		{
			for (int j = i; j < Max; j += i)
			euler[j] = euler[j] / i * (i - 1);
			//先进行除法是为了防止中间数据的溢出
		}
	}
}

int main()
{
    ll n;iii();
    while(~scanf("%lld",&n))
    {
        cout<<euler1(n-1)<<endl;
        //cout<<euler[n-1]<<endl;
    }
    return 0;
}


触类旁通:http://poj.org/problem?id=2407

参考文章 http://blog.csdn.net/qq_27138357/article/details/47399683::模板博客

http://www.hankcs.com/program/algorithm/poj-1284-primitive-roots.html