SOJ 3137: Simple Computing _容斥原理

Time Limit: 2000 MS Memory Limit: 65536 K

Description

Given n integers x1 x2 ... xn, you should count how many intergers from 1 to m that can be divided by at least one of them.

Input

The first line is an integer c which shows the number of cases. Each case contains 2 lines. The first line has 2 integers n and m. The second line contains n integers. (0 < n < 11, 0 < m < 2^31, 0 < xi < 100)

Output

For each case print the answer in a single line.

Sample Input

21 1022 203 4

Sample Output

510

Source

The Star of ACMClub 2007 @ HIT


//题意,给出n个数,求1到m中有多少个数(假设这个数是i)满足n个数中至少有一个数能够整除i;

//变形的求1~n中与m互质的数的个数问题!这里将这n个数直接当做是n个素因子,可以产生多种组合,不断筛选出能够整除1~m中得数的个数,容斥!注意的是,假如n中有两个数3和6,而m=18,对于3*6|18,计算值是1,但是12显然也能够被3、6、3*6整除,所以需要求出这k个数的最小公倍数(需要用long long,没注意错了几次)。


#include<stdio.h>
#include<string.h> 
using namespace std;
#define LL long long
#define maxn 15

int a[maxn];

int gcd(int a,int b)
{
	int c;
	while(b)
	{
		c=b;
		b=a%b;
		a=c;
	}	
	return a;
}

int make_ans(int n,int m)
{
	int ans=0,i,j,flag;
	LL tmp;
	for(i=1;i<(1<<n);i++)
	{
		tmp=1,flag=0;
		for(j=0;j<n&&tmp<=m;j++)
			if(i&(1<<j))
				flag++,tmp=(LL)(a[j]/gcd(tmp,a[j]))*tmp;
		if(flag&1)
			ans+=m/tmp;
		else
			ans-=m/tmp;		
	}
	return ans;
}

int main()
{
	int t,n,m,i;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		printf("%d\n",make_ans(n,m));
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值