POJ - 2478 Farey Sequence

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18768   Accepted: 7554

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

Source

POJ Contest,Author:Mathematica@ZSU

题解:因为数据大,所以要用递归打表,打两个表:一个解题表a[i]和一个欧拉函数表p[i]。

可以发现a[i]=a[i-1]+p[i];p[i]是i与1-i与i互质数的个数即欧拉函数表。

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=1000010;
long long N;
long long a[maxn];
long long p[maxn];
void el(){//欧拉函数表 
	int i,j;
	for(i=1;i<=maxn;i++){
		p[i]=1;
	}
	for(i=2;i<=maxn;i=i+2){
		p[i]=p[i]/2;
	}
	for(i=3;i<=maxn;i=i+2){
		if(p[i]==i){
			for(j=i;j<=maxn;j=j+i){
				p[j]=p[j]/i*(i-1);
			}
		}
	}
} 
void fun(){
	a[2]=1;
	for(int i=3;i<=1000000;i++){
		a[i]=a[i-1]+p[i];
	}
}
int main(){
	el();
	fun();
	while(scanf("%lld",&N)!=EOF&&N){
	    cout<<a[N]<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/henu111/article/details/81459361