---
id: 772
lang: en
translation_of: index.md
source_sha256: 5a68592886700f71dc13a58bbbe90b387f7313c11da2d21eaef234855d29493c
title: "BZOJ2818: GCD — Solution"
description: "Writing x = sa, y = sb with gcd(a, b) = 1, each prime s contributes twice a prefix sum of Euler's totient, minus one."
tags: ["OI","Number Theory","LCM","gcd","Euler's Totient Function"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## 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

```cpp
// 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;
}
```
