算术基本定理+容斥-17级暑假集训(求一个数所有小于这个数并与其互质的数,用到了欧拉函数)

B - Relatives

https://vjudge.net/contest/240973#problem/B

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互质的数的个数。

欧拉函数:φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),其中p1, p2……pn为x的所有质因数,x是不为0的整数。φ(1)=1(唯一和1互质的数就是1本身)。 (注意:每种质因数只一个。比如12=2*2*3

那么φ(12)=12*(1-1/2)*(1-1/3)=4)

代码:

/*
题目描述:n,一个正数,有多少个小于n且与n互质的数?
两个数a,b互质仅当不存在x>1,y>0,z>0满足a=xy且b=xz

Input

多组测试案例。对每一组,标准输入包含一行:n<=1e9
0代表结束

Output

输出只有一行,为问题的答案

思路:
 求出n因子的个数x,用n减去x即为所求 
 但是如何求n因子的个数呢? 
 思路好像出现错误,是用因数知识加上欧拉函数做 
*/ 
#include <stdio.h>
#include <math.h>
int f(long n)
{
	long res=n,x=n,i,z=sqrt(n);
	for(i=2;i<=z;i++)
	{
		if(x%i==0)
		res=res/i*(i-1);//为什么是先除后乘而先乘后除就不对,公式明明没有规定顺序,而且先乘后除貌似合理一些啊 
		while(x%i==0)
		x=x/i;
	}
	if(x>1)
	res=res/x*(x-1);
	return res;
}
int main()
{
	long n;
	while(~scanf("%ld",&n)&&n)
	{
	printf("%ld\n",f(n));	
	}
	return 0;
} 
 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章