Given n, a positive integer, how many positive integers less than n are relatively prime to n? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such that a = xy and b = xz.
Input
There are several test cases. For each test case, standard input contains a line with n <= 1,000,000,000. A line containing 0 follows the last case.
Output
For each test case there should be single line of output answering the question posed above.
Sample Input
7
12
0
Sample Output
6
4
题意:
就是求[1,n)中有多少个数与n互质;
思路:
利用欧拉函数解决;
欧拉函数:
在数论中,对正整数n,欧拉函数是小于或等于n的正整数中与n互质的数的数目。
看了一些博客,其中有一篇举例解释的很通俗易懂,当n=12时,12里面有1/2个数是2的倍数(2,4,6,8,10,12),有1-1/2个不是2的倍数(1,3,5,7,9,11),1-1/2个不是2的倍数里面又有1/3个是3的倍数(3,9),有1-1/3个不是3的倍数(1,5,7,11),所以最后就有4个数与12互质,即12*(1-1/2)*(1-1/3)=4;
贴一份欧拉函数的模板:
int euler(int n)
{
int ans = n;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
{
ans = ans / i * (i - 1);
while (n % i == 0)
n /= i;
}
if (n > 1)
ans = ans / n * (n - 1);
return ans;
}
这题的代码:
(这题题目是说要小于n但是对1这个样例要输出0好像没有特别要求,需要注意一下)
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
#define lowbit(a) (a & (-a))
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
const int minn = 1e6 + 10;
const double PI = acos(-1.0);
#define mod 1000000007
#define eps 1e-10
int euler(int n)
{
int ans = n;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
{
ans = ans / i * (i - 1);
while (n % i == 0)
n /= i;
}
if (n > 1)
ans = ans / n * (n - 1);
return ans;
}
int main()
{
int n;
while (cin >> n, n)
{
cout << euler(n) << endl;
}
return 0;
}