http://acm.split.hdu.edu.cn/showproblem.php?pid=1796
How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9226 Accepted Submission(s): 2767
Problem Description
Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0<N<2^31,0<M<=10, and the M integer are non-negative and won’t exceed 20.
Output
For each case, output the number.
Sample Input
12 2 2 3
Sample Output
7
给一个n,然后给m个数字(不大于20),求若一个数是这m个数字中的任意一个数字的倍数的话,那么这个数字就符合题意,求
【1,n),(不包括n)中有多少个这样的数字。
思路:容斥定理:每一个数字都能求出一些他的倍数,这些数字肯定都是符合题意的,但是有些数字重复计算了,所以要减去(用容斥定理解决),用这m个数字任意组合,个数为奇数则加上,个数为偶数则减去。(奇加偶减)
AC代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#define LL long long
using namespace std;
LL gcd(LL a,LL b)
{
return b==0?a:gcd(b,a%b);
}
LL lcm(LL a,LL b)
{
return a/gcd(a,b)*b;
}
int f[50],lf;
LL check(LL n)
{
LL ans=0;
int k=1<<lf;
for(int i=1; i<k; i++)//枚举任意一个组合情况
{
LL tmp=1;
int flag=0;
for(int j=0; j<lf; j++)
if(i&(1<<j))
{
tmp=lcm(tmp,(LL)f[j]);//求的是最小公倍数,而不是倍数
flag++;//个数
}
if(flag&1) ans+=n/tmp;//奇加偶减
else ans-=n/tmp;
}
return ans;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
int x[20];
lf=0;
for(int i=0; i<m; i++)
{
scanf("%d",&x[i]);
if(x[i]) f[lf++]=x[i];
}
int ans=(int)check((LL)(n-1));
printf("%d\n",ans);
}
return 0;
}