UVA11426 GCD - Extreme (II)
label
Foreword
Concise meaning of the questions
- 求
\[\sum_{i=1}^{n-1}\sum_{j=i+1}^ngcd(i,j)\]
n <=4e6
Thinking
- First request \ (\ sum_ {I}. 1 = n-^ {} \ sum_ {J} = ^ ngcd. 1 (I, J) \) , and then subtracting the diagonal, and finally divided by 2 is the answer. Ij is equal to the diagonal, the diagonal sum gcd is n * (n + 1) / 2
- Then focuses on how to find \ (\ sum_ {i = 1 } ^ {n} \ sum_ {j = 1} ^ ngcd (i, j) \)
- With \ (gcd (i, j) = \ sum_ {d | i and d | j} ^ n \ phi (d) \) inversion of it. This formula is the final answer \ (\ sum_. 1} ^ {n-D = \ Phi (D) * [\ FRAC Nd] ^ 2 \) , divides the block written on the line.
Precautions
- \ (\ phi \) prefix and open long long
to sum up
AC Code
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn = 4e6 + 10;
bool no_prime[maxn];
int prime[maxn];
long long phi[maxn];
int shai(int n)
{
int cnt = 0;
no_prime[1] = phi[1] = 1;
for (int i = 2; i <= n; i++)
{
if (!no_prime[i])
prime[++cnt] = i, phi[i] = i - 1;
for (int j = 1; j <= cnt && prime[j] * i <= n; j++)
{
no_prime[prime[j] * i] = 1;
phi[prime[j] * i] = (i % prime[j] == 0) ? phi[i] * prime[j] : phi[i] * (prime[j] - 1);
if (i % prime[j] == 0) break;
}
}
for (int i = 1; i <= n; i++)
phi[i] += phi[i - 1];
return cnt;
}
void solve()
{
shai(maxn - 10);
while (1)
{
int n;
scanf("%d", &n);
if (n == 0) return;
long long ans = 0;
int l = 1, r;
while (l <= n)
{
r = n / (n / l);
ans += 1ll * (phi[r] - phi[l - 1]) * (n / l) * (n / l);
l = r + 1;
}
printf("%lld\n", (ans - 1ll*n*(n+1)/2) / 2);
}
}
int main()
{
freopen("Testin.txt", "r", stdin);
solve();
return 0;
}