当前位置:网站首页>数学知识:能被整除的数—容斥原理
数学知识:能被整除的数—容斥原理
2022-07-03 01:03:00 【奋斗吧!骚年!】
题目:AcWing 890. 能被整除的数
给定一个整数 n 和 m 个不同的质数 p1,p2,…,pm。
请你求出 1∼n 中能被 p1,p2,…,pm 中的至少一个数整除的整数有多少个。
输入格式
第一行包含整数 n 和 m。
第二行包含 m 个质数。
输出格式
输出一个整数,表示满足条件的整数的个数。
数据范围
1≤m≤16,
1≤n,pi≤109
输入样例:
10 2
2 3
输出样例:
7
题目分析:
该题用到了容斥原理
首先能被m个不同的质数整除,那么可能就会有1、2、3… m个的情况。
我们使用二进制数来枚举所有情况
用S1表示只能被一个数整除的集合个数,S2能被两个数整除的集合个数…
由容斥原理得所有情况为加上奇数个数的集合减去偶数个数的集合。
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 20;
int p[N];
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)cin>>p[i];
int res=0;
for(int i=1;i<1<<m;i++) //枚举所有情况
{
int t=1,s=0; // t表示能被整除的数的乘积,s表示数的个数
for(int j=0;j<m;j++)
{
if(i>>j&1) // 如果选取
{
if((LL)t*p[j]>n) // 如果选取的数大于n
{
t=-1;
break;
}
t *= p[j];
s++;
}
}
if(t!=-1)
{
if(s%2)res+=n/t; //奇数加
else res-=n/t; // 偶数减
}
}
cout<<res<<endl;
return 0;
}
边栏推荐
- 一位苦逼程序员的找工作经历
- Androd Gradle 对其使用模块依赖的替换
- 【第29天】给定一个整数,请你求出它的因子数
- leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
- 按鍵精靈打怪學習-多線程後臺坐標識別
- Database SQL language 02 connection query
- Matlab finds the position of a row or column in the matrix
- [my advanced journey of OpenGL learning] collation of Euler angle, rotation order, rotation matrix, quaternion and other knowledge
- Delete duplicate elements in the ordered linked list -ii
- 如今少年已归来,人间烟火气最抚凡人心 复工了~
猜你喜欢

Strongly connected components of digraph

【FPGA教程案例6】基于vivado核的双口RAM设计与实现

每日一题之干草堆的移动
![leetcode:871. Minimum refueling times [Pat has done before + maximum stacking + greed]](/img/2c/8ec3926243fac8db9ed45d8053f3af.png)
leetcode:871. Minimum refueling times [Pat has done before + maximum stacking + greed]

Androd Gradle 对其使用模块依赖的替换

无向图的割点

1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】

excel IF公式判断两列是否相同

Correctly distinguish the similarities and differences among API, rest API, restful API and web service

攻克哈希的基本概念与实现
随机推荐
Key wizard play strange learning - multithreaded background coordinate recognition
按键精灵打怪学习-多线程后台坐标识别
Embrace the safety concept of platform delivery
2022 cable crane driver examination registration and cable crane driver certificate examination
Machine learning terminology
leetcode:701. 二叉搜索树中的插入操作【bst的插入】
kivy教程之在 Kivy App 中使用 matplotlib 的示例
Button wizard play strange learning - go back to the city to buy medicine and add blood
基本远程连接工具Xshell
[system analyst's road] Chapter V double disk software engineering (development model development method)
MySQL --- 数据库查询 - 条件查询
MySQL basics 03 introduction to MySQL types
【C语言】指针与数组笔试题详解
软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
异步、邮件、定时三大任务
Data analysis, thinking, law breaking and professional knowledge -- analysis method (I)
按键精灵打怪学习-自动回城路线的判断
测试右移:线上质量监控 ELK 实战
用Go+绘制爱心给心爱的她表白
Kivy tutorial - example of using Matplotlib in Kivy app