当前位置:网站首页>数学知识:能被整除的数—容斥原理
数学知识:能被整除的数—容斥原理
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] module dependency replacement of gradle's usage skills
- 【FPGA教程案例6】基于vivado核的双口RAM设计与实现
- 如今少年已归来,人间烟火气最抚凡人心 复工了~
- Excel if formula determines whether the two columns are the same
- Tp6 fast installation uses mongodb to add, delete, modify and check
- Draw love with go+ to express love to her beloved
- Specified interval inversion in the linked list
- FPGA - 7 Series FPGA internal structure clocking -04- multi area clock
- Button wizard play strange learning - automatic return to the city route judgment
- Is there a handling charge for spot gold investment
猜你喜欢
随机推荐
一比特苦逼程序員的找工作經曆
Trois tâches principales: asynchrone, courrier et timing
Kivy教程大全之如何在 Kivy 中创建下拉列表
【无标题】
如今少年已归来,人间烟火气最抚凡人心 复工了~
Embrace the safety concept of platform delivery
Androd gradle's substitution of its use module dependency
信息熵的基础
R language generalized linear model function GLM, (model fit and expression diagnostics), model adequacy evaluation method, use plot function and car package function
Type expansion of non ts/js file modules
d,ldc构建共享库
R language ggplot2 visualization: use ggplot2 to display dataframe data that are all classified variables in the form of thermal diagram, and customize the legend color legend of factor
Button wizard play strange learning - go back to the city to buy medicine and add blood
Asynchronous, email and scheduled tasks
dotConnect for PostgreSQL数据提供程序
2022 Jiangxi Provincial Safety Officer B certificate reexamination examination and Jiangxi Provincial Safety Officer B certificate simulation examination question bank
Leetcode 6103 - minimum fraction to delete an edge from the tree
Several cases of recursive processing organization
Esp32 simple speed message test of ros2 (limit frequency)
MySQL foundation 04 MySQL architecture








