poj2478 Farey Sequence 欧拉函数性质的简单应用

来源:互联网 发布:xt800远程控制软件 编辑:程序博客网 时间:2024/06/05 03:07
Farey Sequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 14014 Accepted: 5539

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,小于n且和n互质的正整数(包括1)的个数,记作φ(n) 。
欧拉函数的两个性质:
第一:大于1的质数x的欧拉函数函数值为x-1,1的欧拉函数值为1.
第二:若a为N的质因数,若(N % a == 0 && (N / a) % a == 0)
则有E(N)=E(N / a) * a;若(N % a == 0 && (N / a) % a != 0)
则有:E(N) = E(N / a) * (a - 1)。

此题可看做是从2到n查找每个数的比自己小且与该数互质的数的个数之和。

#ifdef _MSC_VER  #define DEBUG  #define _CRT_SECURE_NO_DEPRECATE  #endif    #include <fstream>  #include <stdio.h>  #include <iostream>  #include <string.h>  #include <string>  #include <limits.h>  #include <algorithm>  #include <math.h>  #include <numeric>  #include <functional>  #include <ctype.h>  using namespace std;    const int kMAX=1000010;  const double kEPS=10E-6;  int prime[kMAX]={0},num_prime=0;//num_pirme记录素数个数  bool is_prime[kMAX];    void GetPrime(const int m)  {    memset(is_prime,true,sizeof(is_prime));    for(int i=2;i<m;i++)    {      if(is_prime[i])        prime[num_prime++]=i;      for(int j=0;j<num_prime && i*prime[j]<m;j++)      {        is_prime[i*prime[j]]=false;//合数标为1,同时,prime[j]是合数i*prime[j]的最小素因子        if(!(i%prime[j]))//即比一个合数大的质数和该合数的乘积可用一个更大的合数和比其小的质数相乘得到          break;      }    }   }    long long dp[kMAX]={0ll};  void Solve(void)  {      GetPrime(kMAX);      for(int i=2;i<kMAX;++i)      {          if(is_prime[i])              dp[i]=i-1;          else          {              for(int j=0;j<num_prime;++j)                  if(i%prime[j]==0)                  {                      if((i/prime[j])%prime[j]==0)                          dp[i]=dp[i/prime[j]]*prime[j];                      else                          dp[i]=dp[i/prime[j]]*(prime[j]-1);                      break;                  }          }      }      for(int i=3;i<kMAX;++i)          dp[i]+=dp[i-1];  }    int main(void)  {  #ifdef DEBUG      freopen("../stdin.txt","r",stdin);    freopen("../stdout.txt","w",stdout);   #endif        int n,ncase=1;      Solve();    while(~scanf("%d",&n) && n)    {          printf("%lld\n",dp[n]);    }      return 0;  }  


1 0
原创粉丝点击