POJ2478_Farey Sequence【快速求歐拉函數】

來源:互聯網
上載者:User

標籤: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【快速求歐拉函數】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.