poj-2478-Farey Sequence(欧拉函数的应用)

题目链接:http://poj.org/problem?id=2478

Description

The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rational numbers a/b with 0 < a < b <= n and gcd(a,b) = 1 arranged in increasing order. The first few are 
F2 = {1/2} 
F3 = {1/3, 1/2, 2/3} 
F4 = {1/4, 1/3, 1/2, 2/3, 3/4} 
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5} 

You task is to calculate the number of terms in the Farey sequence Fn.

Input

There are several test cases. Each test case has only one line, which contains a positive integer n (2 <= n <= 106). There are no blank lines between cases. A line with a single 0 terminates the input.

Output

For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey sequence Fn. 

Sample Input

2
3
4
5
0

Sample Output

1
3
5
9

题目大意:一个数列:

F2 = {1/2} 
F3 = {1/3, 1/2, 2/3} 
F4 = {1/4, 1/3, 1/2, 2/3, 3/4} 
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5} 

......

观察这个数列很容易就发现规律,第n个数列的元素个数是第n-1数列的元素个数+n的欧拉函数值

给出一个数n,输出该数列的元素个数

很简单,打个表,暴力预处理一下,直接输出

ac:

#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<bitset> 
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  

#define ll long long  
#define INF 0x3f3f3f3f  
#define mod 1000000007
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b) 
#define clean(a,b) memset(a,b,sizeof(a))// 水印 
//std::ios::sync_with_stdio(false);

ll arr[1000010],oula[1000010];

/*ll euler(ll n)
{
	ll res=n;
	for(ll i=2;i*i<=n;++i)
	{
		if(n%i==0)
		{
			res=res/i*(i-1);
			while(n%i==0)
				n=n/i;
		}
	}
	if(n>1)
		res=res/n*(n-1);
	return res;
}*/

void intt()
{
	clean(arr,0);
	clean(oula,0);
	arr[0]=0;
	arr[1]=0;
	oula[1]=1;
	for(int i=2;i<1000010;++i)
	{
		if(oula[i]==0)
		{
			for(int j=i;j<1000010;j=j+i)
			{
				if(oula[j]==0)
					oula[j]=j;
				oula[j]=oula[j]-oula[j]/i;
			}
		}
	}
	for(int i=2;i<1000010;++i)
		arr[i]=arr[i-1]+oula[i];
}

int main()
{
	intt();
	int n;
	while(cin>>n&&n!=0)
		cout<<arr[n]<<endl;
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/81503366