容斥原理 AcWing 890. 能被整除的数
原题链接
算法标签
容斥原理
思路
代码
#include<bits/stdc++.h>
#define int long long
#define abs fabs
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>=b;--i)
using namespace std;
const int N = 20;
int a[N];
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read(), m=read();
rep(i, 0, m){
a[i]=read();
}
int res=0;
// 枚举从1 到 1111...(m个1)的每一个集合状态, (至少选中一个集合)
rep(i, 1, 1<<m){
// t表示质数乘积 cnt表示当前选法集合数量
int t=1, cnt=0;
rep(j, 0, m){
if(i>>j&1){
// 乘积大于n, 则n/t = 0, 跳出这轮循环
if(t*a[j]>n){
t=-1;
break;
}
cnt++;
t*=a[j];
}
}
if(t!=-1){
if(cnt%2){
res+=n/t;
}else{
res-=n/t;
}
}
}
printf("%lld", res);
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈