ABC206 E.Divide Both 容斥

题目链接

在这里插入图片描述
题解:

开始的时候我们需要预处理 [ 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+=cntdcntd

不过,我们容易发现对于题目要求的条件,我们这么求会多算了一些答案。因此我们要容斥处理一下。对于所有在区间 [ 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 2cntd,当 x x x y y y都等于该数时,我们多减了一次,因此要加 1 1 1。这个每次容斥减去的数的大小就是 2 ∗ c n t d − 1 2*cntd-1 2cntd1

实现细节见代码:

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值