题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=2227
Phi 函数 | ||||||
| ||||||
Description | ||||||
输入一个整数 n,输出 phi(n)。 phi(n) 定义为,小于等于 n 且与 n 互质的正整数的数目。 | ||||||
Input | ||||||
输入数据包含一行,包含一个整数 n(1 <= n <= 1000)。 | ||||||
Output | ||||||
输出一行表示对应的答案。 | ||||||
Sample Input | ||||||
10 5 99 | ||||||
Sample Output | ||||||
4 4 60 | ||||||
Hint | ||||||
小于 10 且与 10 互质的数有:1, 3, 7, 9 。 |
由于给的数据范围小,所以无论如何操作都没有问题;
给出两种写法
第一种比较nb点的,效率高,但是相比于第二种需要的空间稍微有点大,其实一点都不大N级别的
#include <iostream>
#include <cstdio>
using namespace std;
int phi[1000005];
void phi_table(int n)
{
for(int i=2; i<=n; ++i)
phi[i]=0;
phi[1]=1;
for(int i=2; i<=n; ++i)
if(!phi[i])
for(int j=i; j<=n; j+=i)
{
if(!phi[j])
phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
int main()
{
int n;
phi_table(10000);
while(~scanf("%d",&n))
printf("%d\n",phi[n]);
return 0;
}
第二种,采用gcd一个一个判断,遍历从1到n就好了,如果最大公因数是1的话就记录一下,运行效率有点低,但是对于1 <= n <= 1000绝对够用了
#include <iostream>
#include <cstdio>
using namespace std;
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
int main()
{
int n;
while(~scanf("%d", &n))
{
int ans = 0;
for(int i = 1;i <= n; i++)
if(gcd(i, n) == 1)
ans++;
printf("%d\n", ans);
}
return 0;
}