首页 > 代码库 > POJ2478 Farey Sequence
POJ2478 Farey Sequence
Farey Sequence
Time Limit: 1000MS | Memory Limit: 65536K | |
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.
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
23450
Sample Output
1359
Source
POJ Contest,Author:Mathematica@ZSU
欧拉函数模板题,16ms的O(n)线性筛,代码是抄贾教的。。
Codes:
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 int n,phi[1001000],tot,prime[500000]; 5 long long sum[1001000]; 6 bool check[1000100]; 7 void PHI(int n){ 8 phi[1] = 1; 9 for(int i=2;i<=n;i++){10 if(!check[i]){11 prime[++tot] = i;12 phi[i] = i - 1;13 }14 for(int j=1;j<=tot;j++){15 if(prime[j]*i>n) break;16 check[prime[j]*i] = true;17 if(i%prime[j]==0){18 phi[i*prime[j]] = phi[i] * prime[j];19 break;20 }else phi[i*prime[j]] = phi[i] * (prime[j]-1);21 }22 }23 }24 25 int main(){26 PHI(1000000);27 sum[2] = 1;28 for(int i=3;i<=1000000;i++) sum[i]+=sum[i-1] + phi[i];29 while(scanf("%d",&n)!=EOF && n) cout<<sum[n]<<endl;30 return 0;31 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。