<h1 style="COLOR: #1a5cc8"><span style="white-space:pre"> </span>How many integers can you find</h1><span size="+0" style=""><strong><span style="font-size: 12px; font-family: Arial; color: green;">Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5026 Accepted Submission(s): 1425
</span></strong></span>
<div class="panel_title" align="left">Problem Description</div><div class="panel_content"> 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.</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Input</div><div class="panel_content"> 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.</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Output</div><div class="panel_content"> For each case, output the number.</div><div class="panel_bottom"> </div>
<div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="FONT-FAMILY: Courier New,Courier,monospace">12 2
2 3</div>
Sample Output
7
题意:
求1->n-1之间能被一个集合A内元素整除的数的个数,例如n = 12, A = {2, 3} 则能被A集合元素整除的数的集合为{2, 3, 4 , 6, 8, 9, 10}则结果为7。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int n,m,cnt;
long long ans,a[30];
long long gcd(long long a,long long b){
return b==0?a:gcd(b,a%b);
}
void DFS(int cur,long long lcm,int id){
lcm=a[cur]/gcd(a[cur],lcm)*lcm;
if(id&1)
ans+=(n-1)/lcm; //因为这题并不包含n本身,所以用n-1
else
ans-=(n-1)/lcm;
for(int i=cur+1;i<cnt;i++)
DFS(i,lcm,id+1);
}
int main(){
//freopen("input.txt","r",stdin);
while(~scanf("%d%d",&n,&m)){
cnt=0;
int x;
while(m--){
scanf("%d",&x);
if(x!=0) //除0
a[cnt++]=x;
}
ans=0;
for(int i=0;i<cnt;i++)
DFS(i,a[i],1);
cout<<ans<<endl;
}
return 0;
}