当前位置:网站首页>数学知识:能被整除的数—容斥原理
数学知识:能被整除的数—容斥原理
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;
}
边栏推荐
- MySQL basic usage 02
- Basic concept and implementation of overcoming hash
- 强化学习 Q-learning 实例详解
- Makefile中wildcard、patsubst、notdir的含义
- MySQL
- Cut point of undirected graph
- Excel calculates the difference between time and date and converts it into minutes
- [androd] module dependency replacement of gradle's usage skills
- Canvas drawing -- bingdd
- The latest analysis of tool fitter (technician) in 2022 and the test questions and analysis of tool fitter (technician)
猜你喜欢
[untitled]
用Go+绘制爱心给心爱的她表白
MySQL basics 03 introduction to MySQL types
Detailed explanation of Q-learning examples of reinforcement learning
Matlab saves the digital matrix as geospatial data, and the display subscript index must be of positive integer type or logical type. Solve the problem
电话网络问题
MySQL --- 数据库查询 - 基本查询
Excel if formula determines whether the two columns are the same
Matlab Doppler effect produces vibration signal and processing
Leetcode 2097 - Legal rearrangement of pairs
随机推荐
【我的OpenGL学习进阶之旅】关于欧拉角、旋转顺序、旋转矩阵、四元数等知识的整理
MySQL foundation 05 DML language
Type expansion of non ts/js file modules
Matlab finds the position of a row or column in the matrix
按键精灵打怪学习-前台和内网发送后台验证码
软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
有向图的强连通分量
The R language uses the ctree function in the party package to build conditional inference decision trees, uses the plot function to visualize the trained conditional inference decision tree, and the
按鍵精靈打怪學習-多線程後臺坐標識別
Telephone network problems
LDC Build Shared Library
MySQL foundation 07-dcl
Kivy tutorial how to create drop-down lists in Kivy
基本远程连接工具Xshell
ThinkPHP+Redis实现简单抽奖
合并K个已排序的链表
Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens
leetcode:701. 二叉搜索树中的插入操作【bst的插入】
Key wizard play strange learning - multithreaded background coordinate recognition
【FPGA教程案例5】基于vivado核的ROM设计与实现