题目链接:POJ-2478
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 <= 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
题意就是给定n,求出所有分母小于等于n的真分数个数。
思路很清晰,即求出小于等于n的数 的欧拉函数之和。
直接将n以内所有数字质因数分解后求欧拉函数是一定会超时的,所以我们要用更快速的方法求欧拉函数表。
法一:Eratosthenes筛法 复杂度 O(NlogN),用时250ms
Eratosthenes的筛法基于 对任意x的整数倍数,2x,3x,… 都不是质数。从2开始,从小到大扫描每个数X,把它的倍数2x,3x,…,floor(N/x)*x标记为合数。当扫描到一个数时,如果它尚未标记,则它一定不能被2~x-1之间的任何数整除,该数就是质数。
又因为实际上小于等于x^2的x的倍数在扫描更小的数时就已经被标记过了,因此,我们可以对Eratosthens筛法进行优化。对于每个数x,我们只需要从x^2开始,把x^2,(x+1)*x,…,floor(N/x)*x标记为合数即可。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>
#include <queue>
#include <set>
#define eps 1e-8
typedef long long ll;
const double PI = acos(-1.0);
const int maxn = 1e6;
const int INF = 1e9;
const ll linf = 0x3f3f3f3f3f3f3f3f;
using namespace std;
int n;
ll phi[maxn+5];
void euler(int n)
{
for(int i = 2; i<=n; i++)
phi[i] = i;
for(int i = 2; i<=n; i++)
{
if(phi[i] == i)
{
for(int j = i*i; j<=n; j += i)
phi[j] = phi[j]/i*(i-1);
}
}
}
int main()
{
euler(maxn);
for(int i = 3; i<=1e6; i++)
{
//cout<<phi[i]<<endl;
phi[i] += phi[i-1];
}
while(scanf("%d",&n) != EOF && n)
{
cout<<phi[n]<<endl;
}
return 0;
}
法二:线性筛 复杂度O(N),用时63ms
1.若p|n且p^2|n,则phi(n) = phi(n/p)*p
2.若p|n但p^2不能整除n,则phi(n) = phi(n/p)*(p-1)
在线性筛法中,每个合数n只会被它的最小质因子p筛一次。我们恰好可以在此时执行以上两条判断,从phi(n/p)递推到phi(n)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>
#include <queue>
#include <set>
#define eps 1e-8
typedef long long ll;
const double PI = acos(-1.0);
const int maxn = 1e6;
const int INF = 1e9;
const ll linf = 0x3f3f3f3f3f3f3f3f;
using namespace std;
int n,cnt;
int v[maxn+5],prime[maxn+5];
ll phi[maxn+5];
void euler(int n)
{
memset(v,0,sizeof v);
cnt = 0;
for(int i = 2; i<=n; i++)
{
//i是质数
if(v[i] == 0)
{
v[i] = i;
prime[cnt++] = i;
phi[i] = i-1;
}
//给当前的数i乘上一个质因子
for(int j = 0; j<cnt; j++)
{
//i有比prime[j]更小的质因子或超出n的范围
if(prime[j]>v[i] || prime[j]>n/i)
break;
//prime[j]是i*prime[j]的最小质因子
v[i*prime[j]] = prime[j];
phi[i*prime[j]] = phi[i]*(i%prime[j] ? prime[j]-1:prime[j]);
}
}
}
int main()
{
euler(maxn);
for(int i = 3; i<=1e6; i++)
{
//cout<<phi[i]<<endl;
phi[i] += phi[i-1];
}
while(scanf("%d",&n) != EOF && n)
{
cout<<phi[n]<<endl;
}
return 0;
}