【ZOJ - 2836】【Number Puzzle】(容斥定理)

题目:

Given a list of integers (A1, A2, ..., An), and a positive integer M, please find the number of positive integers that are not greater than M and dividable by any integer from the given list.

 

Input

 

 

The input contains several test cases.

For each test case, there are two lines. The first line contains N (1 <= N <= 10) and M (1 <= M <= 200000000), and the second line contains A1, A2, ..., An(1 <= Ai <= 10, for i = 1, 2, ..., N).

 

Output

 

For each test case in the input, output the result in a single line.

 

Sample Input

 

3 2
2 3 7
3 6
2 3 7
 

 

Sample Output

 

1
4

解题报告:确实刚上来是真的看不懂题目是意思,求解小于等于m的数能被数组中的n个数整除的数目和。打算直接遍历走完是不现实的,因为m的范围太大了, 所以想到了容斥定理,数组中的每个数字能被整除的数目的求并,自然引出容斥定理,然后套模板,最后做差输出即可。

ac代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int num[15],n,m;
int gcd(int a,int  b)
{
	if(b==0)
		return a;
	else
		return gcd(b,a%b);	
} //最大公因子 
int lcm(int a,int b)
{
	return a/gcd(a,b)*b;
}//最小公倍数 
int dfs(int pos,int val)
{
	if(pos==n)
	{
		return m/val;
	}
	return dfs(pos+1,val)-dfs(pos+1,lcm(val,num[pos]));
}
//容斥定理 
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(int i=0;i<n;i++)
			scanf("%d",&num[i]);
		printf("%d\n",m-dfs(0,1));
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值