Description
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
Source
这道题提供了一个O(sqrt(n))求单个数phi函数的方法——我们把答案设为n,考虑从小到大枚举n的因数,一个一个把这些因数的倍数给排除,同时把这些因数从n除开。因为我们是从小到大枚举的,而且每一次会除开枚举过的因数,这样我们不会有多减的和少减的。细节可以看代码:
#include<cstdio>
using namespace std;
int a;
int getphi(int x) {
int ans = x;
for(register int i = 2; i <= x; ++i)
if(x % i == 0){
ans -= ans / i;
while(x % i == 0)
x /= i;
}
if(x != 1) ans -= ans / x;
return ans;
}
int main() {
while(1) {
scanf("%d", &a);
if(!a) break;
printf("%d\n", getphi(a));
}
return 0;
}
rockdu
没有帐号? 立即注册