1. 程式人生 > >Newcoder 39 E.集合中的質數(容斥原理)

Newcoder 39 E.集合中的質數(容斥原理)

Description

給出一個集合和一個數 m m

集合裡面有 n n 個質數。

請你求出從$ 1$ 到$ m $的所有數中,至少能被集合中的一個數整除的數的個數。

Input

第一行兩個正整數$ n$ 和$ m $。

第二行 n n 個正整數,分別為集合中的質數。

( n 20 , 1

m 2 63 1 , p
1 0 9 ) (n\le 20,1\le m\le 2^{63}-1,p\le 10^9)

Output

輸出一個整數,表示符合要求的正整數的個數。

Sample Input

3 37
5 7 13

Sample Output

13

Solution

給出的都是素數,直接容斥即可,時間複雜度 O ( n 2 n ) O(n\cdot 2^n)

Code

#include<cstdio>
using namespace std;
typedef long long ll;
int n,a[22];
ll m;
int main()
{
	scanf("%d%lld",&n,&m);
	for(int i=0;i<n;i++)scanf("%d",&a[i]);
	int N=1<<n;
	ll ans=0;
	for(int i=1;i<N;i++)
	{
		ll res=m;
		int num=0;
		for(int j=0;j<n;j++)
			if((i>>j)&1)num++,res/=a[j];
		if(num&1)ans+=res;
		else ans-=res;
	} 
	printf("%lld\n",ans);
	return 0;
}