B - Farey Sequence

POJ - 2478

欧拉函数求前缀和

把分数按照分母分类,每一类的个数为\(\phi(分母)\)

\(\frac{1}{1}\)特判掉

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int N = 1000050;

int p[N + 5],prime[N],cnt;
long long phi[N + 5];

int main(){
    phi[1] = 1;
    for(int i = 2; i <= N; ++ i){
        if(!p[i]) { prime[++ cnt] = i; phi[i] = i - 1; }
        for(int j = 1; j <= cnt && 1ll * prime[j] * i <= N; ++ j){
            p[prime[j] * i] = 1;
            if(i % prime[j] == 0) { phi[prime[j] * i] = phi[i] * prime[j]; break; }
            phi[prime[j] * i] = phi[prime[j]] * phi[i];
        }
    }
    
    for(int i = 1; i <= N; ++ i) phi[i] += phi[i - 1];
    
    int n;
    while(1){
        scanf("%d",&n);
        if(!n) break;
        printf("%lld\n",phi[n] - 1);
    }
    return 0;
}

posted @ 2020-07-24 16:33  zhuzihan  阅读(110)  评论(0编辑  收藏  举报