hdu2824 快速求欧拉函数

欧拉函数的定义可以自己百度 phi(n)=n*(1-1/p1)*(1-1/p2)*...(1-1/pn)

主要是涉及到求很多个欧拉函数时的求法,这种题一般都是先初始化,

其中,在求素因子的时候处理的很巧妙,当phi[i]==i时,i就是素因子(可以拿起笔在草稿上画一下就明白了),这个时候j+=i, 则j有素因子i,认真思考!

之前做过一道题,是求一个数的所以因子之和,也是类似的做法:

Problem Description

  The hardest problem may not be the real hardest problem.
  Given a natural number n (1 <= n <= 500000), please output the summation of all its proper divisors. Definition: A proper divisor of a natural number is the divisor that is strictly less than the number. e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.

Input

An integer stating the number of test cases (equal to about 200000), and that many lines follow, each containing one integer between 1 and 500000 inclusive.

Output

One integer each line: the divisor summation of the integer given respectively.

Sample Input

3
2
10
20

Sample Output

1
8
22

关键代码如下:

void init()
{
 int i, j;
 memset(a, 0, sizeof(a));
 for (i = 1; i < 500001; i++)
  for (j = i + i; j < 500001; j += i)
   a[j] += i;  //a[j]表示j的所有因子之和,不包括本身
}

hdu2824本题的代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

#define bint __int64
#define N 3000001

bint phi[N];

void init()
{
    int i, j;
    for(i = 1; i < N; i++)
        phi[i] = i;

    for(i = 2; i < N; i++)
        if(i == phi[i]) //此时i为素数
            for(j = i; j < N; j += i)  //j累加i
                phi[j] = (phi[j] / i) * (i - 1); //j有因子i,而且i是素数,正是欧拉函数
}

int main()
{
    init();
    int a, b;
    while(scanf("%d%d", &a, &b) != EOF)
    {
        bint ans = 0;
        for(int i = a; i <= b; i++)
            ans += phi[i];
        printf("%I64d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(百度,Integer,less,input,each,output)