zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    ASP.Net控件基础篇
    ASP.Net
    有关于静态
    重载
    继承和多态
    面向对象的封装
    .net webform 把word转为html
    lambda 表达式 比较时间大小
    js 根据名字获取cookie 的方法
    .net 常用的命名空间和类
  • 原文地址:https://www.cnblogs.com/fx1998/p/13458970.html
Copyright © 2011-2022 走看看