欧拉函数 AcWing 874. 筛法求欧拉函数
原题链接
算法标签
数学知识 欧拉函数 线性筛法
思路
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
#define x first
#define y second
using namespace std;
const int N = 1e6+5;
int phi[N], st[N], pr[N];
int cnt=0;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
int eul(int n){
phi[1]=1;
for(int i=2;i<=n;++i){
if(!st[i]){
pr[cnt++]=i;
phi[i]=i-1;
}
for(int j=0;pr[j]<=n/i;++j){
st[pr[j]*i]=true;
if(!(i%pr[j])){
phi[t]=phi[i]*pr[j];
break;
}
phi[t]=phi[i]*(pr[j]-1);
}
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read();
int res=0;
eul(n);
rep(i, 1, n+1){
res+=phi[i];
}
printf("%lld", res);
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈