Rewrite the given sum as follows:
Group the terms in the sum by their common factor:
The same factor appears in all terms. Factor it out:
Implement a sieve that computes all values of Euler's totient function from to 10^4 and stores them in the array. Then, build an array of partial sums , where
After that, for each input value , print the product
Example
Consider the state of the array containing the values of Euler's totient function and the array containing the partial sums:
For n = 10, the answer is
Algorithm implementation
Declare the arrays and , where:
fi[i] = φ(i);
sum[i] = φ(1) + φ(2) + ... φ(i)
#define MAX 10001
long long fi[MAX], sum[MAX];The FillEuler function fills the array with the values of Euler's totient function:
void FillEuler(void)
{
int i, j;
for (i = 0; i < MAX; i++) fi[i] = i;
for (i = 2; i < MAX; i++)
if (fi[i] == i)
for (j = i; j < MAX; j += i)
fi[j] -= fi[j] / i;Compute the partial sums . Initialize the first elements of the array.
sum[0] = 0; sum[1] = 1;Then, compute the remaining partial sums sequentially.
for(i = 2; i < MAX; i++)
sum[i] = sum[i-1] + fi[i];
}The main part of the program. Fill the and arrays.
FillEuler();Process test cases:
scanf("%d",&tests);
while(tests--)
{
scanf("%d",&n);For each input value , compute and print the answer
res = sum[n] * sum[n];
printf("%lld\n",res);
}