CodeChef - CDSW153 Virat and his challenge(容斥原理)

题意:

给一个区间[L,R]求这个区间内能被小于n的素数,整除的数的个数。

解析:

容斥原理,虽然不能马上求出[L,R]区间内的答案,但是可以利用容斥原理转化为求[0,L-1]区间内的个数和[0,R]区间内的个数。
最终答案就是 [0,R] - [0,L-1]

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
ll n, l, r;

int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
ll solve(int size) {
    ll end = 1 << size, ans = 0;
    for(ll i = 1; i < end; i++) {
        ll cnt = 0, num = 1;
        for(ll j = 0; j < size; j++) {
            if(i & (1 << j)) {
                num *= prime[j];
                cnt++;
            }
        }
        if(cnt & 1) {
            ans += (r / num - (l-1) / num);
        }else {
            ans -= (r / num - (l-1) / num);
        }
    }
    return ans;
}
int main() {
    int T;
    scanf("%d" ,&T);
    while(T--) {
        scanf("%lld%lld%lld", &n ,&l ,&r);
        int idx = upper_bound(prime, prime + 16, n) - prime;
        printf("%lld\n", solve(idx));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值