Sieve method for Euler function ----------------------- template (number theory)

Given a positive integer n, find the sum of the Euler functions for each number from 1 to n.

The input format
consists of one line and contains an integer n.

The output format
has one line and contains an integer, which represents the sum of the Euler functions of each number in 1 ~ n.

Data range
1≤n≤106
Input sample:
6
Output sample:
12

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+1000;
typedef long long ll;
ll phi[N];
ll prime[N],cnt;
bool st[N];
int n;
void slove(int n)
{
    phi[1]=1;
    memset(st,true,sizeof st);
    for(int i=2;i<=n;i++)
    {
        if(st[i]) 
        {
            prime[++cnt]=i;
            phi[i]=i-1;
        }
        for(int j=1;j<=cnt&&prime[j]<=n/i;j++)
        {
            st[prime[j]*i]=false;
            if(i%prime[j]==0)
            {
                phi[i*prime[j]]=phi[i]*prime[j];
                break;
            }
            phi[i*prime[j]]=phi[i]*(prime[j]-1);
        }
    }
    ll sum=0;
    for(int i=1;i<=n;i++) sum+=phi[i];
    cout<<sum<<endl;
}
int main()
{
    cin>>n;
    slove(n);
}
Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105246969