UVa 10820 Send a Table(欧拉函数)

题意:

求n以内的 互素对的个数对于数对(x,y)(x<y)是互素对的话 则(y,x)也是互素对

思路:

http://www.csie.ntnu.edu.tw/~u91029/Prime.html

欧拉函数:

n = p1^a1 × p2^a2 × … × pk^ak   where p1 … pk are primes

φ(n) = n × (1 - 1/p1) × (1 - 1/p2) × … × (1 - 1/pk)

可以化简求法为:n ÷ p1 × (p1-1) ÷ p2 × (p2-1) ÷ … ÷ pk × (pk-1)

代码中用了筛选素数的方法来实践上式,可谓精妙。

//
// http://www.csie.ntnu.edu.tw/~u91029/Prime.html
//
#include <cstdio>
#include <cstdlib>
#include <cstring>

const int MAXN = 50010;
int phi[MAXN];

void phi_table()
{
    memset(phi, 0, sizeof(phi));
    phi[1] = 1;
    for (int i = 2; i < MAXN; ++i)
        if (!phi[i])
            for (int j = i; j < MAXN; j += i)
            {
                if (!phi[j])
                    phi[j] = j;
                phi[j] = phi[j] / i * (i - 1);
            }

}

int main()
{
    int n;
    phi_table();
    while (scanf("%d", &n) && n)
    {
        int ans = phi[1];
        for (int i = 2; i <= n; ++i)
            ans += phi[i] << 1;
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2012-12-05 11:03  kedebug  阅读(264)  评论(0编辑  收藏  举报