当前位置:网站首页>数学知识:能被整除的数—容斥原理
数学知识:能被整除的数—容斥原理
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 foundation 07-dcl
- Key wizard hit strange learning - automatic path finding back to hit strange points
- MySQL
- matlab 多普勒效应产生振动信号和处理
- leetcode:871. Minimum refueling times [Pat has done before + maximum stacking + greed]
- JS inheritance and prototype chain
- [androd] module dependency replacement of gradle's usage skills
- 每日一题之干草堆的移动
- MySQL --- 数据库查询 - 条件查询
- [FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
猜你喜欢

MySQL - database query - basic query

How wide does the dual inline for bread board need?

Basic remote connection tool xshell

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

Basic concept and implementation of overcoming hash

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

Excel if formula determines whether the two columns are the same

一比特苦逼程序員的找工作經曆

FPGA - 7 Series FPGA internal structure clocking -04- multi area clock

Telephone network problems
随机推荐
Strongly connected components of digraph
kivy教程之在 Kivy App 中使用 matplotlib 的示例
2022 coal mine gas drainage examination question bank and coal mine gas drainage examination questions and analysis
Inversion de l'intervalle spécifié dans la liste des liens
leetcode:701. Insertion in binary search tree [BST insertion]
按键精灵打怪学习-回城买药加血
matlab查找某一行或者某一列在矩阵中的位置
Makefile中wildcard、patsubst、notdir的含义
LDC Build Shared Library
Esp32 simple speed message test of ros2 (limit frequency)
How wide does the dual inline for bread board need?
一位苦逼程序员的找工作经历
Excel if formula determines whether the two columns are the same
MySQL --- 数据库查询 - 基本查询
Find a benchmark comrade in arms | a million level real-time data platform, which can be used for free for life
leetcode 6103 — 从树中删除边的最小分数
Create your first Kivy program Hello word (tutorial includes source code)
Button wizard play strange learning - automatic return to the city route judgment
Database SQL language 01 where condition
[shutter] animation animation (shutter animation type | the core class of shutter animation)