標籤:des style blog http io os ar for sp
Farey SequenceTime Limit: 1000MSMemory Limit: 65536KTotal Submissions: 12377Accepted: 4808Description
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:[email protected]
題目大意:
給你一個數n,對於0 < a < b <= n,求真分數a/b的個數
思路:因為a/b為真分數,所以a和b互質。
求真分數a/b的個數。其實就是求0 < i <= n中,小於i的正整數中,
有多少個與i互質的數。累加起來就是真分數a/b的個數。
其實就是歐拉函數
因為n的規模為10^6,可用快速求歐拉函數的方法求得(類似於篩法求素數)。
根據推論:設P是素數,
若p是x的約數,則E(x*p)=E(x)*p.
若p不是x的約數,則E(x*p)=E(x)*E(p)=E(x)*(p-1).
根據篩法求素數的方法,由E(x)求得E(x*p)。
參考博文:http://www.cppblog.com/RyanWang/archive/2009/07/19/90512.html
#include<stdio.h>int prime[100010],phi[1000010];bool unprime[1000010];__int64 sum[1000010];void Euler(){ int i,j,k = 0; for(i = 2; i <= 1000000; i++) { if(!unprime[i]) { prime[k++] = i; phi[i] = i-1; } for(j = 0; j < k && prime[j]*i <= 1000000; j++) { unprime[prime[j] *i] = true; if(i % prime[j] != 0) { phi[prime[j]*i] = phi[i]*(prime[j]-1); } else { phi[prime[j]*i] = phi[i]*prime[j]; break; } } }}int main(){ int i,n; Euler(); for(i = 1; i <= 1000000; i++) sum[i] = sum[i-1] + phi[i]; while(~scanf("%d",&n) && n) { printf("%I64d\n",sum[n]); } return 0;}
POJ2478_Farey Sequence【快速求歐拉函數】