Nk 1214 Relatives(欧拉函数)
Time Limit: 1500 ms Memory Limit: 10000 kB
Total Submit : 234 (77 users) Accepted Submit : 102 (72 users) Page View : 3852
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
0
AC代码:任何一个整数都能用质因数形式表示如:60=2^2*3^1*5^1 所以for循环中小的质因数被除点剩下从小到大循环中能整除的一定是它质因数
#include<iostream> #include<cmath> using namespace std; int euler_phi(int n) { int m=sqrt(n+0.5); int ans=n; for(int i=2;i<=m;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_phi(n)<<endl; return 0; }