Relatives
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 15597 Accepted: 7922
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
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 15597 Accepted: 7922
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
题意:给你一个数n,求小于n的数与n互质的数的个数,裸欧拉函数
欧拉函数给大家安利一个好博客,就有一点,用中国剩余定理证明欧拉函数是积性函数我不是太明白,毛估估知道他要表达什么但不是很懂。还有就是朋友告诉我的理解欧拉函数的一个办法,不官方我加上自己的理解叙述一下。
从欧拉函数的公式入手,其中p1,p2是组成n的质因子,那么我们分析一下简单的数,比如12,12=(2^2)*(3^1),那么欧拉函数就是φ(12)=12*(1-1/2)*(1-1/3)。
我们想,想要得到与12互质的数,那么含有2,3的数肯定不行,剃出了他们其他的肯定可以,1,2,3,4,5,6,7,8,9,10,11,12,它们之中含有2的数各一个就出现一次,那么含有二的数占了总数的1/2,同理含有3的数占了1/3那么提出它们剩下的就是(1-1/2)*(1-1/3),最后用12乘一下就是我们要的答案。
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
long long euler(long long n)
{
long long ans=n;
for(long long i=2;i*i<=n;i++)
{
if(n%i==0)//开始的时候是2,3这种,n肯定会含有
{
ans=ans/i*(i-1);//公式变下型
while(n%i==0)//剔除所有2
n/=i;
}
}
if(n!=1)//跑一边以后还不是1的话说明其中还会含有其他质因子
ans=ans/n*(n-1);
return ans;
}
int main()
{
long long n;
while(~scanf("%lld",&n))
{
if(n==0)
break;
printf("%lld\n",euler(n));
}
}