求解欧拉函数值

/*************************************************************************
    > File Name:        phi.cpp
    > Author:         wangzhili
    > Mail:           wangstdio.h@gmail.com
    > Created Time:   2014年03月17日 星期一 21时05分09秒
 ************************************************************************/
#include<iostream>                  //求解欧拉函数值(小于等于n的数中与n互质的数的个数);
using namespace std;
const int MAX = 1111111;
int minDiv[MAX], phi[MAX], sum[MAX];
void getphi(){
    for(int i = 1;i <= MAX;i ++){
        minDiv[i] = i;
    }
    for(int i = 2;i * i < MAX;i ++){        //求解j的最小质因数;
        if(i == minDiv[i]){
            for(int j = i * i;j < MAX;j += i){
                minDiv[j] = i;
            }
        }
    }
    phi[1] = 1;
    for(int i = 2;i < MAX;i ++){
        phi[i] = phi[i / minDiv[i]];
        if((i / minDiv[i]) % minDiv[i] == 0){
            phi[i] *= minDiv[i];
        }else{
            phi[i] *= (minDiv[i] - 1);
        }
    }
}

int main(){
    int n;
    getphi();
    while(cin >> n){
        cout << phi[n] << endl;
    }
    return 0;
}


posted on 2014-04-30 18:37  wangzhili  阅读(139)  评论(0编辑  收藏  举报