poj3030(欧拉函数2 O(n))

用O(n),算法优化

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn=2000;

int phi[maxn],totans[maxn],prime[maxn],v[maxn];

int getphi(int n){
    int top=0;
    for (int i=2;i<=n;i++){
        if(v[i]==0){
            prime[++top]=i;
            v[i]=i;
            phi[i]=i-1;
        }
        for (int j=1;j<=top;j++){
            if(prime[j]>v[i]||prime[j]>n/i) break;
            v[i*prime[j]]=prime[j];
            phi[i*prime[j]]=phi[i]*(i%prime[j]?prime[j]-1:prime[j]);//if prime[i]整除n,且prime[i]*prime[i]整除n,那么phi[n]=phi[n/prime[i]]*prime[i]
            //else phi[n]=phi[n/prime[i]]*prime[i]-1;
        }
    }
}

int main(){
    int n;
    scanf("%d",&n);
    int v;
    phi[1]=1;
    getphi(1010);
    for (int i=2;i<=1010;i++){
        totans[i]=phi[i]+totans[i-1];
    }
    for (int i=1;i<=n;i++){
        scanf("%d",&v);
        printf("%d %d %d\n",i,v,totans[v]*2+3);
    }
return 0;
}

 

posted @ 2018-05-25 19:32  lmjer  阅读(152)  评论(0编辑  收藏  举报