How many integers can you find
Time Limit: 5000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 179664-bit integer IO format: %I64d Java class name: Main
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
Source
解题:容斥原理,注意有0
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn = 20; 5 int a[maxn],n,m; 6 LL LCM(LL a,LL b){ 7 return a/__gcd(a,b)*b; 8 } 9 int main(){ 10 while(~scanf("%d%d",&n,&m)){ 11 int tot = m; 12 for(int i = m = 0,tmp; i < tot; ++i){ 13 scanf("%d",&tmp); 14 if(tmp) a[m++] = tmp; 15 } 16 LL ret = 0; 17 for(int i = 1; i < (1<<m); ++i){ 18 LL lcm = 1; 19 int cnt = 0; 20 bool flag = false; 21 for(int j = 0; j < m; ++j){ 22 if((i>>j)&1){ 23 cnt++; 24 lcm = LCM(lcm,a[j]); 25 if(lcm < 0){ 26 flag = true; 27 break; 28 } 29 } 30 } 31 if(flag) continue; 32 if(cnt&1) ret += (n - 1)/lcm; 33 else ret -= (n - 1)/lcm; 34 } 35 printf("%I64d ",ret); 36 } 37 return 0; 38 }