码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 2836 Number Puzzle(容斥原理啊)

时间:2015-04-14 19:43:21      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:zoj   数学   容斥原理   

题目链接: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


Author: MAO, Yiqiang
Source: Zhejiang University Local Contest 2007


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;
}


ZOJ 2836 Number Puzzle(容斥原理啊)

标签:zoj   数学   容斥原理   

原文地址:http://blog.csdn.net/u012860063/article/details/45046519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!