码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2478_Farey Sequence【快速求欧拉函数】

时间:2014-10-15 23:10:51      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   os   ar   for   sp   

Farey Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12377 Accepted: 4808
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

题目大意:

给你一个数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【快速求欧拉函数】

标签:des   style   blog   http   io   os   ar   for   sp   

原文地址:http://blog.csdn.net/lianai911/article/details/40116329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!