Problem Description
Multiple query, for each n, you need to get
n i-1
∑ ∑ [gcd(i + j, i - j) = 1]
i=1 j=1
Input
On the first line, there is a positive integer T, which describe the number of queries. Next there are T lines, each line give a positive integer n, as mentioned above.
T<=1e5, n<=2e7
Output
Your output should include T lines, for each line, output the answer for the corre- sponding n.
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=6434
小知识:如果 a 与 b 互质,a、b和(a + b)互质。
所以题目求的是a、b互质并且a+b == i * 2的数有几对。a + b == i * 2, 所以就是求所有与i*2互质的数的个数 / 2。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int maxn = 2e7+5;
int phi[maxn * 2], prim[maxn * 2];
void get_ouler() {
memset(phi, 0, sizeof phi);
phi[1] = 1;
int id = 0;
for(int i = 2; i < maxn * 2; i++) {
if(!phi[i]) {
phi[i] = i - 1;
prim[id++] = i;
}
for(int j = 0; j < id && prim[j] * i < maxn * 2; j++) {
if(i % prim[j]) {
phi[i * prim[j]] = phi[i] * (prim[j] - 1);
} else {
phi[i * prim[j]] = phi[i] * prim[j];
break;
}
}
}
}
ll sum[maxn] = {0};
void init() {
for(int i = 2; i < maxn; i++)
sum[i] = phi[i * 2] / 2 + sum[i - 1];
}
int main()
{
get_ouler();
init();
int T, n;
scanf("%d", &T);
while(T--){
scanf("%d", &n);
printf("%lld\n", sum[n]);
}
return 0;
}