hdu1796---How many integers can you find(容斥原理)

容斥入门题
计算同时被1个数整除的,减去同时被2个整除,加上同时被3个整除的….
被多个数同时整除,就是被这些数的lcm整除,注意0

/************************************************************************* > File Name: hdu1796.cpp > Author: ALex > Mail: [email protected] > Created Time: 2015年05月26日 星期二 21时13分05秒 ************************************************************************/

#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>

using namespace std;

const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;

vector <int> st;
int numb[15];

LL gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}

int main() {
    int n, m;
    while (~scanf("%d%d", &n, &m)) {
        for (int i = 0; i < m; ++i) {
            scanf("%d", &numb[i]);
        }
        int ans = 0;
        --n;
        for (int i = 1; i < (1 << m); ++i) {
            int cnt = 0;
            int cur = 1;
            for (int j = 0; j < m; ++j) {
                if (i & (1 << j)) {
                    ++cnt;
                    cur = cur / gcd(cur, numb[j]) * numb[j];
                }
            }
            if (cur == 0) {
                continue;
            }
            if (cnt & 1) {
                ans += n / cur;
            }
            else {
                ans -= n / cur;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

你可能感兴趣的:(容斥原理)