hdu1796容斥

http://acm.hdu.edu.cn/showproblem.php?pid=1796

求n能被m个数中任意数整除的个数;
就是n能被一个数整除的个数减去能被两个数整除的个数(即两个数的最小公倍数)加上能被三个数同时整除的个数……

#include <iostream>
#include <cstdio>
using namespace std;

typedef long long LL;

int gcd(int a, int b)
{
    if(b==0)return a;
    return gcd(b,a%b);
}
int lcm(int a,int b)
{
    return a/gcd(a,b)*b;
}
int main()
{
    int n,m;
    int a[15];
    while (cin>>n>>m)
    {
        for (int i = 0; i < m; ++i)
        {
            cin>>a[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 = lcm(cur,a[j]);
                }
            }
            if (cur == 0)
            {
                continue;
            }
            if (cnt & 1)
            {
                ans += n / cur;
            }
            else
            {
                ans -= n / cur;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

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