[AcWing 890] 能被整除的数

点击查看代码
#include<iostream>
using namespace std;
typedef long long LL;
const int N = 20;
int n, m;
int p[N];
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i ++) cin >> p[i];
int res = 0;
for (int i = 1; i < 1 << m; i ++) {
int t = 1, cnt = 0;
for (int j = 0; j < m; j ++) {
if (i >> j & 1) {
cnt ++;
if ((LL) t * p[j] > n) {
t = -1;
break;
}
t *= p[j];
}
}
if (t != -1) {
if (cnt % 2) res += n / t;
else res -= n / t;
}
}
cout << res << endl;
return 0;
}
- 容斥原理 (转自 OI Wiki)

证明:(用到了 $ (1 - 1)^{m} $ 的二项展开)

- 采用位运算的方式,第 i 位(从后往前数)上为 1,代表有集合 i,若集合里面元素个数为奇数,则加上,为偶数则减去
- 因为 $ p_i $ 均为质数,这些质数的乘积就是它们的最小公倍数,n 除这个最小公倍数就是交集的大小

浙公网安备 33010602011771号