Luogu UVA12995 Farey Sequence (Eulerian function, linear sieve)

Luogu Topic Portal

Fractions are actually a pretense, which is actually to find the number of pairs of co-prime numbers (except for a special case \((1,1)\) ). Because \(a<b\) is guaranteed , so let's disassemble the required things, isn't it \(\sum_{i=2}^n\phi(i)\) ?

A little idea of ​​linearly finding the Euler function by sieving primes is summarized in Konjac 's blog

All that's left is to remember a prefix sum.

#include<cstdio>
#define R register
const int N=1000001;
int pr[N],phi[N];
long long ans[N];
bool f[N];
int main(){
    R int n,i,j,k,p=0;
    for(i=2;i<N;++i){
        if(!f[i])phi[pr[++p]=i]=i-1;
        ans[i]=ans[i-1]+phi[i];
        for(j=1;j<=p&&(k=i*pr[j])<N;++j){
            f[k]=1;
            if(i%pr[j])
                phi[k]=phi[i]*(pr[j]-1);
            else{
                phi[k]=phi[i]*pr[j];
                break;
            }
        }
    }
    while(scanf("%d",&n),n)
        printf("%lld\n",ans[n]);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324875178&siteId=291194637