题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1836
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
PS:http://www.cnblogs.com/BigBallon/p/4072487.html
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define LL long long
LL n, m;
LL a[17];
LL GCD(LL a, LL b)
{
if(b == 0)
return a;
return GCD(b,a%b);
}
LL LCM(LL a, LL b)
{
return a*(b/GCD(a,b));
}
int main()
{
while(~scanf("%lld %lld",&n,&m))
{
for(int i = 0; i < n; i++)
{
scanf("%lld",&a[i]);
}
LL ans = 0;
for(int i = 1; i < (1<<n); i++)//用二进制枚举(遍历)选择的情况
{
LL tt = 1;
LL num = 0;
for(int j = 0; j < n; j++)
{
if((1<<j) & i)
{
tt = LCM(tt,a[j]);
num++;
}
}
if(num & 1)
{
ans += m/tt;
}
else
{
ans -= m/tt;
}
}
printf("%lld\n",ans);
}
return 0;
}
原文:http://blog.csdn.net/u012860063/article/details/45046519