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
求解与n(1-n-1)互质的质因子的个数
解析:(转)
定义:对于正整数n,φ(n)是小于或等于n的正整数中,与n互质的数的数目。
例如:φ(8)=4,因为1,3,5,7均和8互质。
性质:1.若p是质数,φ(p)= p-1.
2.若n是质数p的k次幂,φ(n)=(p-1)*p^(k-1)。因为除了p的倍数都与n互质
3.欧拉函数是积性函数,若m,n互质,φ(mn)= φ(m)φ(n).
根据这3条性质我们就可以推出一个整数的欧拉函数的公式。因为一个数总可以写成一些质数的乘积的形式。
E(k)=(p1-1)(p2-1)...(pi-1)*(p1^(a1-1))(p2^(a2-1))...(pi^(ai-1))
= k*(p1-1)(p2-1)...(pi-1)/(p1*p2*...*pi)
= k*(1-1/p1)*(1-1/p2)...(1-1/pk)
在程序中利用欧拉函数如下性质,可以快速求出欧拉函数的值(a为N的质因素)
若( N%a ==0&&(N/a)%a ==0)则有:E(N)= E(N/a)*a;
若( N%a ==0&&(N/a)%a !=0)则有:E(N)= E(N/a)*(a-1);
文章原链接:http://www.cnblogs.com/jackge/archive/2013/01/03/2842818.html
下面看一下欧拉函数的模板吧:
int eular(int n)
{
int res=1,i;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
n/=i;
res*=i-1;
while(n%i==0)
{
n/=i;
res*=i;
}
}
}
if(n>1) res*=n-1;
return res;
}
对于求与n互质的数的个数这个题,记住模板直接套就完事了。
AC代码如下:
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<map>
#include<vector>
#include<set>
#include<iostream>
const int mod =1e9+7;
using namespace std;
typedef long long ll;
#include<stdio.h>
int eular(int n)
{
int res=1,i;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
n/=i;
res*=i-1;
while(n%i==0)
{
n/=i;
res*=i;
}
}
}
if(n>1) res*=n-1;
return res;
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
{
printf("%d\n",eular(n));
}
return 0;
}