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<=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
思路:欧拉函数的前缀和,关于欧拉函数详见文章:浅谈欧拉函数
AC代码:
#include<cstdio>
#include<iostream>
#define int long long
using namespace std;
const int N=1000005;
int phi[N],num[N],sum[N];
bool isnp[N];
void euler(int n){
int ant=0;
phi[1]=1;
for(int i=2;i<=n;i++){
if(!isnp[i]){
num[++ant]=i;
phi[i]=i-1;
}
for(int j=1;j<=ant&&i*num[j]<=n;j++){
isnp[i*num[j]]=1;
if(i%num[j]==0){
phi[i*num[j]]=phi[i]*num[j];
break;
}
phi[i*num[j]]=phi[i]*phi[num[j]];
}
}
}
signed main(){
//注意!!!一定要减 否则数组会溢出!!!
euler(N-5);//初始化 求前1000000个数的欧拉函数
//求前缀和
for(int i=2;i<=N-5;i++){
sum[i]=sum[i-1]+phi[i];
}
int n;
while(cin>>n){
//多组输入以0结束的题目一定要这样写!!!
if(n==0){
break;
}
cout<<sum[n]<<endl;
}
return 0;
}