eduR 181 C 题解

· · 题解

思路

考虑统计 f(x) 为 [1,x] 内的好数个数。

正难则反,考虑统计不好的数的个数。不好的数就是质因子中含一位数的数,一位的质数只有 2,3,5,7。那么 f(x) 就是 x 减去 [1,x] 内 2,3,5,7 的倍数个数。

考虑容斥,2,3,5,7 的倍数个数就是单个数的倍数个数之和,减去其中任意两个数的公倍数的数的个数之和,加上其中任意两三数的公倍数的数的个数之和,减去四个数的公倍数个数之和。x 以内的 y 的倍数有 \left\lfloor\frac{x}{y}\right\rfloor 个,所以可以得出:

S\leftarrow\{2,3,5,7\}\\ p^k(x)=\sum_{T\subseteq S,\text{card}(T)=k}\left\lfloor\frac{x}{\prod T}\right\rfloor\\ f(x)=\sum_{i=0}^4 p^i(x)\times(-1)^i

还是看代码比较好理解一些,时间复杂度 O(t)。

代码

#include<bits/stdc++.h>
using namespace std;
#define ep emplace
#define eb emplace_back
#define ef emplace_front
#define ll long long
int T;
ll l,r;
vector<int> p1 = {2,3,5,7,30,42,70,105},p2 = {6,10,14,15,21,35,210};//p1 为减去的因子,p2 为加上的因子
inline ll f(ll r){
    ll rtn = r;
    for(auto i : p1) rtn -= r / i;
    for(auto i : p2) rtn += r / i;
    return rtn;
}
int main(){
    cin.tie(0)->sync_with_stdio(0);
    cin >> T;
    while(T --){
        cin >> l >> r;
        printf("%lld\n",f(r) - f(l - 1));
    }
    return 0;
}