题解:
开始的时候我们需要预处理 [ l , r ] [l,r] [l,r]区间内大于 1 1 1的倍数个数。这样 g c d ( x , y ) ! = 1 gcd(x,y)!=1 gcd(x,y)!=1的个数其实就是所有大于 1 1 1且小于等于 r r r的倍数个数平方之和,也就是 a n s + = c n t d ∗ c n t d ans+=cntd*cntd ans+=cntd∗cntd。
不过,我们容易发现对于题目要求的条件,我们这么求会多算了一些答案。因此我们要容斥处理一下。对于所有在区间 [ l , r ] [l,r] [l,r]内的数,要减去其与其倍数组成的数对个数,也就是 c n t d cntd cntd,由于 x x x和 y y y都可以等于该数,因此要减去 2 ∗ c n t d 2*cntd 2∗cntd,当 x x x和 y y y都等于该数时,我们多减了一次,因此要加 1 1 1。这个每次容斥减去的数的大小就是 2 ∗ c n t d − 1 2*cntd-1 2∗cntd−1。
实现细节见代码:
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int MAXN = 1e6 + 10;
const int mod = 1e9 + 7;
int l, r;
int cnt[MAXN], _cnt[MAXN];
void init() {
for (int i = 2; i < 1e6 + 5; i++) { // 埃筛预处理倍数个数
for (int j = i; j <= r; j += i) {
if (j < l) continue;
cnt[i]++;
}
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> l >> r;
init();
int ans = 0;
for (int i = r; i >= 2; i--) {
_cnt[i] = cnt[i] * cnt[i];
for (int j = i * 2; j <= r; j += i) {
_cnt[i] -= _cnt[j];
}
ans += _cnt[i];
if (i >= l) {
ans -= 2 * cnt[i] - 1; // 减去x或y等于i的情况
}
}
cout << ans << endl;
return 0;
}