1. 程式人生 > 實用技巧 >22.能被整除的數 容斥原理

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 }