Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0<N<2^31,0<M<=10, and the M integer are non-negative and won’t exceed 20.
Output
For each case, output the number.
Sample Input
12 2
2 3
Sample Output
7
题目翻译:
现在,您得到一个数字N和一个M整数集合,您应该找出多少个小于N的整数,它们可以精确地除以集合中的任何整数。 例如,N = 12,并且M整数集为{2,3},因此还有另一个集{2,3,4,6,8,9,10},该集的所有整数都可以精确地除 乘2或3。结果,您只需输出数字7。
输入项
有很多情况。 对于每种情况,第一行包含两个整数N和M。第二行包含M个整数,并且它们彼此不同。 0 <N <2 ^ 31,0 <M <= 10,并且M整数为非负且不会超过20。
输出量
对于每种情况,输出数字。
样本输入
12 2
2 3
样本输出
7
解题思路:对于数字N,用M中的每个数去整除,然后计算数量,肯定有重复的,通过容斥原理,可以知道n(A∪B∪C…)=n(A)+n(B)+n©…-n(A∩B)-n(A∩C)-n(B∩C)…+n(A∩B∩C)…,对于m中的数进行二进制枚举,偶数就减去,奇数就加上
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
ll n;
ll s[100];
vector<ll> q;
ll gcd(ll a,ll b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
ll lcm(ll a,ll b)//最小公倍数
{
return a*b/gcd(a,b);
}
ll solve(int s)
{
ll ans=0;
//二进制枚举
for(ll i=1;i<(1<<s);i++){
ll p=1;
int cnt=0;
for(ll j=0;j<s;j++){
if((1<<j)&i){
p=lcm(p,q[j]);
cnt++;
}
}
if(cnt&1)
ans+=(n-1)/p;//奇数次加上
else
ans-=(n-1)/p;//偶数次减去
}
return ans;
}
int main()
{
int m;
while(~scanf("%lld%d",&n,&m)){
q.clear();
int f=0;
for(int i=0;i<m;i++){
scanf("%lld",&s[i]);
}
sort(s,s+m);
for(int i=0;i<m;i++){
if(s[i]<=0)
continue;
for(int j=i+1;j<m;j++){
if(s[j]%s[i]==0)//去掉重复的,提升性能
s[j]=-1;
}
q.push_back(s[i]);
}
ll ans=solve(q.size());
printf("%lld\n",ans);
}
return 0;
}