22.能被整除的数 容斥原理

 

 

 所以一共会有2 ^ n项,时间复杂度O(2 ^ n)

 用容斥原理来做的话,时间复杂度就是2 ^ 16 * 16

用位运算来枚举所有情况,从1枚举到2 ^ n - 1

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int N = 20;
 5 int p[N];
 6 int main() {
 7     int n, m;
 8     cin >> n >> m;
 9     for (int i = 0; i < m; i++) {
10         cin >> p[i];
11     }
12     int res = 0;
13     for (int i = 1; i < (1 << m); i++) {
14         int t = 1, s = 0;
15         //t表示当前所有质数的乘积
16         //s表示当前包含几个1,也就是当前这个选法里有几个集合
17         for (int j = 0; j < m; j++) { //枚举m位
18             if (i >> j & 1) {
19                 s++;
20                 if ((ll)t * p[j] > n) {
21                     t = -1;
22                     break;
23                 }
24                 t *= p[j];
25             }
26         } 
27         if (t != -1) {
28             if (s % 2) { //奇数加,偶数减
29                 res += n / t;
30             } else {
31                 res -= n / t;
32             }
33         }
34     }
35     cout << res << endl;
36     return 0;
37 }
原文地址:https://www.cnblogs.com/fx1998/p/13458970.html