Y - Farey Sequence

虽然菜,但不甘于菜;

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

一个欧拉函数模板题,求phi数组,之前还一直好奇为什么不用把素数都筛选出来,然后看到有2个if判断的时候知道啦,

公式就是的连乘n(1-1/pi);

这个模板在刘汝佳的算法竞赛入门数论基础的计数那个板块;

刚刚才知道可以插入代码,23333;大笑

难得的一发ac;贴下代码;

#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
using namespace std;
const int N=1e6+5;
typedef long long ll;
ll phi[N];

void Find_phi()
{
    memset(phi,0,sizeof(phi));
    for(ll i=2;i<=N;i++)
        if(!phi[i])
        for(ll j=i;j<N;j+=i)
        {
        if(!phi[j]) phi[j]=j;
        phi[j]=phi[j]/i*(i-1);
        }
}
int main()
{
    //freopen("input.txt","r",stdin);
    int n;
    Find_phi();
    while(~scanf("%d",&n)&&n)
    {
        ll sum=0;
        for(ll i=1;i<=n;i++)
            sum+=phi[i];
            printf("%lld\n",sum);
    }
    return 0;
}



全部评论

相关推荐

12-07 16:16
已编辑
四川大学 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务