http://acm.pku.edu.cn/JudgeOnline/problem?id=2478
Farey Sequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5575 | Accepted: 1998 |
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 <= 10
6). 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
题目大意:求第n个farey序列有多少个分数。或者说,求2~n的欧拉函数的和。
分析:第一种说法,我不知道递推公式是什么,朴素的话会超时,所以按第二种理解方式来解决这道题。
先解释下欧拉函数。欧拉函数用e(n)来表示的话,e(n)表示比n小且与n互质的数的个数。
朴素的方法在本题中行不通,因为数据规模很大。
注意到欧拉函数的性质:e(p)=p-1(p为素数);e(p^k)=p^k-p^(k-1);(p为素数)e(p*q)=e(p)*e(q)。(p、q互质)
有了这些性质,可以通过质因数分解来求欧拉函数。
先用筛选法求出质数,然后对于每个数n,找到一个质数p,p是n的约数。若n/p能整除p,那么e(n)=e(n/p)*p,不然e(n)=e(n/p)*(p-1)。
codes: