BZOJ2818: GCD — Solution
Main Idea
At first glance, this can actually be tied to Euler's totient function. What we want is the number of ordered pairs with \(gcd(x,y) \in Prime, x, y \leq N\). Let that prime be \(s\); then it can be rewritten as:
\[ \begin{gathered} x = sa, y = sb \\ gcd(a, b) = 1 \end{gathered} \]
Hmm, I can see the shadow of Euler's totient function. For each prime \(s\), its contribution to the answer is:
\[ 2 * \sum_{ 1 \leq i \leq \lfloor \frac{n}{s} \rfloor } \phi(i) - 1 \]
Let me explain: since \(x,y \leq n\), we have \(sa \leq n\) and \(sb \leq n\), which gives:
\[ a,b \leq \frac{n}{s} \]
So there are this many pairs. Since these are ordered pairs, multiply by two, then remove the duplicate ordered pairs like \((i,i)\) to get the answer. Note that you can optimize with prefix sums of the totient values.
Code
// BZ2818.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 10000005;
ll n, phi[MAX_N];
bool isPrime[MAX_N];
int main()
{
//memset(isPrime, true, sizeof(isPrime));
scanf("%lld", &n);
for (int i = 2; i <= n; i++)
phi[i] = i;
for (int i = 2; i <= n; i++)
if (!isPrime[i])
for (int j = i; j <= n; j += i)
{
if (j != i)
isPrime[j] = true;
phi[j] = phi[j] / i * (i - 1);
}
phi[1] = 1;
for (int i = 2; i <= n; i++)
phi[i] += phi[i - 1];
long long ans = 0;
for (int i = 2; i <= n; i++)
if (!isPrime[i])
ans += 2 * phi[n / i] - 1;
printf("%lld", ans);
return 0;
}