题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1286
Problem Description
新年快到了,“猪头帮协会”准备搞一个聚会,已经知道现有会员N人,把会员从1到N编号,其中会长的号码是N号,凡是和会长是老朋友的,那么该会员的号码肯定和N有大于1的公约数,否则都是新朋友,现在会长想知道究竟有几个新朋友?请你编程序帮会长计算出来。
Input
第一行是测试数据的组数CN(Case number,1<CN<10000),接着有CN行正整数N(1<n<32768),表示会员人数。
Output
对于每一个N,输出一行新朋友的人数,这样共有CN行输出。
Sample Input
2 25608 24027
Sample Output
7680 16016
题解:
对于任意大于1的正整数n,在1...n-1中有φ(n) 个数与n互质,φ(n)称为欧拉函数。
欧拉函数公式: φ(n) = n * ∑(1-1/pi) (pi为n的质因数)。
推论: 当n为质数时,φ(n)=n - 1.
n的质因数之和 = φ(n) * n / 2.
#include <cstdio>
#include <cstring>
using namespace std;
// 欧拉函数
int Euler(int n) {
int cnt = n;
int temp = n;
// 找质因数
for(int i = 2;i * i <= temp;i++) {
if(temp % i == 0) {
cnt = cnt / i * (i-1);
}
while(temp % i == 0) temp /= i;
}
if(temp > 1)
cnt = cnt / temp * (temp-1);
return cnt;
}
int main()
{
int t;
scanf("%d",&t);
while(t--) {
int n;
scanf("%d",&n);
printf("%d\n",Euler(n));
}
return 0;
}