Euler Numbers
/*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
#include <iostream>
#include<cmath>
#include <algorithm>
using namespace std;
int Euler(int n)
{
int ret=n,p;
for( p=2;p*p<=n;p++)
{
if(n%p==0)
{
ret=ret/p*(p-1);
while(n%p==0)
n/=p;
}
}
if(n>1)
ret=ret/n*(n-1);
// 注意与后面的比较,时间更快,只有一个比sqrt(n)大的一个素数因子
return ret;
}
int main()
{
int n;
while(scanf("%d",&n),n)
printf("%d\n",Euler(n));
return 0;
}
#include <iostream>
#include<cmath>
#include <algorithm>
using namespace std;
int Euler(int n)
{
int ret=n,p;
for( p=2;p<=n;p++)
{
if(n%p==0)
{
ret=ret/p*(p-1);
while(n%p==0)
n/=p;
}
}
if(n>1)
ret=ret/p*(p-1);
return ret;
}
int main()
{
int n;
while(scanf("%d",&n),n)
printf("%d\n",Euler(n));
return 0;
}
浙公网安备 33010602011771号