UVa 10820 - Send a Table 欧拉函数模板

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_problem&problem=1761


题意很简单,理解一下就是输出1 到 n内有多少种两两互质的情况,其中 a 和 b 互质,b 和 a 互质视为不同的情况,很明显就是算欧拉函数。

 

#include<cmath>
#include<cstdio>
#include<memory.h>
#include<algorithm>
using namespace std;
const int MAXN = 50000 + 5;

int N;
int dp[MAXN];
int phi[MAXN];

//筛法求 1 - n 内所有数的欧拉函数的值
void phiTable(int n)
{
    memset(phi, 0, sizeof(phi));
    phi[1] = 1;

    for(int i = 2; i < n; ++ i)
        if(phi[i] == 0)
            for(int j = i; j < n; j += i)
            {
                if(phi[j] == 0)
                    phi[j] = j;

                phi[j] = phi[j] / i * (i - 1);
            }
}

void init()
{
    phiTable(MAXN);
    memset(dp, 0, sizeof(dp));
    dp[1] = 1;

    for(int i = 2; i < MAXN; ++ i)
        dp[i] += dp[i - 1] + (phi[i] << 1);
}

int main()
{
    init();

    while(scanf("%d", &N) != EOF && N)
        printf("%d\n", dp[N]);

    return 0;
}
View Code

 

posted @ 2014-06-08 14:46  Tank..  阅读(144)  评论(0编辑  收藏  举报