容斥原理的证明过程:

如果一个元素在k个集合中出现了2次,那么在计算的过程中会被重复的加2次,所以需要减去。

如果出现了三次,那么在计算的过程中会被重复的减去,则需要加上

image-20220930200909868

题目:// httpss://www.acwing.com/problem/content/892/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// httpss://www.acwing.com/problem/content/892/

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 20;
int p[N];
int n, m;
typedef long long LL;
int main()
{
cin >> n>> m;
for (int i = 0; i < m; i ++) cin >> p[i];
int res = 0;
// 枚举1 到 1111 ... m个 集合,
for (int i= 1; i < 1 << m; i ++)
{
int t = 1; // 所选集合对应的质数乘积。
int s = 0; //所选集合的数量
for (int j = 0; j < m; j ++)
if (i >> j & 1)
{
// 如果大于n,则说明在n中没有所选集合的最小公倍数
if ((LL)t * p[j] > n)
{
t = - 1;
break;
}
t *= p[j];
s ++;
}
//如果t==-1,则说明在n中没有所选集合的最小公倍数
if (t == -1) continue;
if (s & 1) res += n / t; // 根据公式可得, 奇数相加
else res -= n / t; //偶数相减
}

cout << res << endl;

return 0;
}