牛客数论专题 14686 集合中的质数(dfs/数论(容斥原理))

https://ac.nowcoder.com/acm/problem/14686

题目描述 
给出一个集合和一个数m。

集合里面有n个质数。

请你求出从 1 到 m 的所有数中,至少能被集合中的一个数整除的数的个数。
示例1
输入
3 37
5 7 13
输出
13

备注:
对于100%的数据,有n<=20,m为有符号64位正整数,集合内质数<=1000000000
//如果集合中只有一个数,那么答案就是m/a1
//如果 集合中只有两个数,那么答案等于m/a1+m/a2-m/lcm(a1,a2),
//(能被a1整除的数的个数加上能被a2整除的数的个数再减去既能被a1整除又被a2整除的个数)
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const LL N=200200,M=2002;
LL n,m;
LL a[N];
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    //给定了n个数字(都是质数)
    //求在区间[1,n]之间能够至少能整除集合中的任意一个数的数量
    cin>>n>>m;
    for(int i=0;i<n;i++)
        cin>>a[i];
    int ans=0;
    //n向左移动,表示为2的n-1次方
    for(int i=1;i<(1<<n);i++)//取与不取
    {
        int x=m;//满足条件的数的个数
        int num=0;//攻取了几个,奇+偶➖
        for(int j=0;j<n;j++)
        {
            if(i&(1<<j))//每一位取还是不取
            {
                num++;
                x/=a[j];
            }
        }
        if(num%2==1) ans+=x;
        else ans-=x;
    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2022-09-03 16:40  高尔赛凡尔娟  阅读(112)  评论(0编辑  收藏  举报