1. 程式人生 > >Number Puzzle(容斥原理)

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 題目連結 參考題解

題目大意就是給 n 個整數,和一個整數 m。求小於等於 m 的非負整數(1~ m )中能被這N個數中任意一個整除的數的個數。 答題思路就是利用容斥原理,如題解所說:設S1為1 ~ M中能被第一個整數A1整除的集合,S2為1~M中能被第二個整數A2整除的集合。 …… Sn為1~M中能被第N個整數An整除的集合。然後每個集合個數,其實就是M / An。 再根據容斥原理,求集合並集的元素個數即可。 其中要用到 lcm ,具體看程式碼就懂了。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
const int max_a = 10 + 5, maxn = 1e3 + 5;
ll factor[max_a], que[maxn];
ll n, m;

ll gcd(ll a, ll b)
{
    return !b ? a : gcd(b, a % b);
}

ll lcm(ll a, ll b)
{
    return a / gcd(a, b) * b;
}

ll solve()
{
    ll ans = 0;
    //這裡列舉每一種情況,可以想象成一種小型的狀壓,每一個二進位制位都是一個存在狀態
    //也就是他給出的n個數,每一位代表一個數是否存在,存在為1,否則為0,
    //從1到1<<n也就枚舉了所有可能出現的乘法組合
    for(int i = 1; i < (1 << n); ++i)
    {
        ll odd = 0, Lcm = 1;
        //如果當前乘法組合中有和這個數那麼就進行lcm運算
        for(int j = 0; j < n; ++j)
        {
            if((1 << j) & i)
            {
                odd++;
                Lcm = lcm(Lcm, factor[j]);
            }
        }
        //容斥原理,奇數加偶數減
        if(odd & 1)
            ans += m / Lcm;
        else
            ans -= m / Lcm;
    }
    return ans;
}

int main()
{
    while(~scanf("%lld%lld", &n, &m))
    {
        for(int i = 0; i < n; i++)
            scanf("%lld", &factor[i]);
        ll ans = solve();
        printf("%lld\n", ans);
    }
    return 0;
}