欧拉筛,题解来自:https://www.luogu.org/space/show?uid=34195
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <vector> 5 #include <cmath> 6 #include <string> 7 #include <cstring> 8 #include <set> 9 #include <map> 10 using namespace std; 11 const int maxn=40001; 12 int n,cnt,num,m[maxn],phi[maxn],p[maxn]; 13 14 void olershai() 15 { 16 phi[1]=1; 17 for(int i=2;i<=n;++i){ 18 if(!m[i]){ 19 p[++num]=i; 20 phi[i]=i-1; 21 } 22 for(int j=1;j<=num&&p[j]*i<n;++j){ 23 m[p[j]*i]=1; 24 if(i%p[j]==0){ 25 phi[p[j]*i]=phi[i]*p[j]; 26 break; 27 }else{ 28 phi[p[j]*i]=phi[i]*(p[j]-1); 29 } 30 } 31 } 32 } 33 34 int main() 35 { 36 scanf("%d",&n); 37 if(n==1){ 38 printf("0"); 39 return 0; 40 } 41 42 olershai(); 43 for(int i=2;i<n;++i){ 44 cnt+=phi[i]; 45 } 46 cnt*=2; 47 cnt+=3; 48 printf("%d",cnt); 49 return 0; 50 }
。。