首页 > 代码库 > ZOJ 2836

ZOJ 2836

求不比M大的可以被集合任一个数整除的数的个数。(容斥原理)

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int set[15];int ans;int gcd(int a,int b){	if(b==0) return a;	return gcd(b,a%b);}void dfs(int i,int num,int p,int m,int n){	if(i>=n){		if(num==0)		ans=0;		else if(num&1)		ans+=(m/p);		else ans-=(m/p);		return;	}	dfs(i+1,num,p,m,n);	dfs(i+1,num+1,p/gcd(p,set[i])*set[i],m,n);}int main(){	int n,m;	while(scanf("%d%d",&n,&m)!=EOF){		for(int i=0;i<n;i++)		scanf("%d",&set[i]);		dfs(0,0,1,m,n);		printf("%d\n",ans);	}	return 0;}

  

 

ZOJ 2836