LightOJ

来源:互联网 发布:淘宝怎么购物和付款 编辑:程序博客网 时间:2024/06/05 04:05

题目:
Mathematically some problems look hard. But with the help of the computer, some problems can be easily solvable.

In this problem, you will be given two integers a and b. You have to find the summation of the scores of the numbers from a to b (inclusive). The score of a number is defined as the following function.

score (x) = n2, where n is the number of relatively prime numbers with x, which are smaller than x

For example,

For 6, the relatively prime numbers with 6 are 1 and 5. So, score (6) = 22 = 4.

For 8, the relatively prime numbers with 8 are 1, 3, 5 and 7. So, score (8) = 42 = 16.

Now you have to solve this task.

Input
Input starts with an integer T (≤ 105), denoting the number of test cases.

Each case will contain two integers a and b (2 ≤ a ≤ b ≤ 5 * 106).

Output
For each case, print the case number and the summation of all the scores from a to b.

Sample Input
3
6 6
8 8
2 20
Sample Output
Case 1: 4
Case 2: 16
Case 3: 1237
Hint
Euler’s totient function applied to a positive integer n is defined to be the number of positive integers less than or equal to n that are relatively prime to n. is read “phi of n.”

Given the general prime factorization of , one can compute using the formula

题意:

输入T,表示测试组数。输入a,b。表示区间。要将区间a到b的所有数的欧拉数的平方加起来输出。

解题思路:

因为数据较大,直接套公式挨个求解,肯定超时,这个时候就需要根据欧拉函数性质打表了。 φ(p) = p – 1 (p为素数)   若m,n互质,φ(nm) = φ(m) * φ(n)。至于代码稍后给出。如果只是简单打表,这个题还是会超时,需要进一步优化。这个时候就需要前缀和了。前缀和指把当前项到开始第一项都加起来。用处在代码中可以体现。如果只是这样,还是会wa。因为数据太大。即使是long long也会溢出。那么这个时候就需要无符号长整型了。AC.

代码:

//欧拉函数  打表  前缀和  无符号long long # include <cstdio># include <cstring># define ll unsigned long long  //定义ll代表无符号整型using namespace std;ll phi[5000002];void oula(ll 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);            }        }    }} int main(){    int T;    int l,r;    int p = 1;    oula(5000001);    for(int i = 2;i <= 5000000;i++)  //依照规则求前缀和    {        phi[i] = phi[i-1] + phi[i] * phi[i];    }    scanf("%d",&T);    while(T--)    {        scanf("%d %d",&l,&r);   //因为前缀和求出,相减就行,这样时间就大大优化        printf("Case %d: %llu\n",p++,phi[r] - phi[l-1]);    }     return 0;}