UVA 10325 - The Lottery ( 容斥 )

本文介绍了解决UVa在线评测题的方法,即计算从1到n的整数中,不能被输入的m个特定数中的任何一个整除的数的数量。通过应用容斥原理,该问题被简化为计算质数的使用情况。详细步骤包括将问题转换为计算质数能被m个数中的一个整除的数的个数,并最终得到结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1266

题        意:求出1~n个数中不能被输入的m个数任意一个数整除的数的个数。

思        路:利用容斥原理计算n-(1^n中质数能被m个数中的一个整除的数的个数。

                     例如样例一:10-能被2整除的数-能被3整除的数+能被6(即2与3的最小公倍数)整除的数;

                             样例二:20-能被2整除的数-能被4整除的数+能被4(即2与4的最小公倍数)整除的数。

代码如下:

#include <iostream>
using namespace std;
#include <string.h>
#include <stdio.h>
#include <climits>
#include <algorithm>
#define maxn  65535
typedef long long LL;
LL vis[33];
LL gcd( LL a, LL b )
{
    return b?gcd(b,a%b):a;
}
int main()
{
    int n, m;
    while( scanf ( "%d %d", &n, &m ) != EOF )
    {
        for( int i = 0; i < m; i ++ )
            scanf ( "%lld", &vis[i] );
        int sum = 0;
        for( int i = 1; i < ( 1 << m ); i ++ )
        {
            LL mu = 1, ones = 0;
            for( int j = 0; j < m; j ++ )
                if( i & (1<<j) )
                {
                    mu = vis[j]/gcd(mu,vis[j])*mu;
                    if( mu > n ) break;
                    ones++;
                }
            if( mu > n ) continue;
            if( ones%2==1) sum += n/mu;
            else sum -= n/mu;
        }
        printf("%d\n",n-sum);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值