[AcWing 890] 能被整除的数

image


点击查看代码
#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;
}

  1. 容斥原理 (转自 OI Wiki)
    image

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

image

  1. 采用位运算的方式,第 i 位(从后往前数)上为 1,代表有集合 i,若集合里面元素个数为奇数,则加上,为偶数则减去
  2. 因为 $ p_i $ 均为质数,这些质数的乘积就是它们的最小公倍数,n 除这个最小公倍数就是交集的大小
posted @ 2022-05-14 21:54  wKingYu  阅读(29)  评论(0)    收藏  举报