[容斥] LightOJ 1117 - Helping Cicada

LightOJ 1117 - Helping Cicada

题意:给个正整数n,然后给m个整数,求1~n有多少个数不能被这m个数中任意一个整除。(1 <= n < 2^31, m <= 15)

思路:裸容斥,考虑1个数k,1~n有[n/k]个数能被k整除,[a]表示a向下取整,所以ans= n-SIGMA([n/num[i]])(1<=i<=m)。再考虑2个数a,b,因为被a整除同时被b整除这部分减了两次,所以要加上,ans += n/lcm(a,b),枚举2个数,又发现3个数的多加了,再减去3个的,再加上4个的,减去5个的,以此类推。

#include
#define ll long long int
using namespace std;
ll num[16];
int f[2] = {1, -1};
ll gcd(ll a, ll b){ return b? gcd(b, a%b) : a; }
ll lcm(ll a, ll b){ 
    if(a < b) swap(a, b);
    return a/gcd(a,b)*b;
}
int main(){
    int T, ca = 1;
    scanf("%d", &T);
    while(T--){
        ll n, m;
        scanf("%lld%lld", &n, &m);
        for(int i = 0; i < m; ++i) scanf("%lld", num+i);
        ll ans = n, MXM = (1<


你可能感兴趣的:(ACM,题解)