题目不难,有些细节没想到。。。。
求出能够至少被BLN的某个数字整除的数字的个数很好求。要满足BUN中至少有一个数字不能整除这个幸运数,排除掉能被BUN中所有数字最小公倍数整除的数字后就完了。
也就是用容斥原理求[low,high]满足BLN集合条件的x的时候,减去[low,high]能整除lcm(x,bm)的个数(bm是指BUN中所有数字的公倍数)
还有就是最小公倍数可能会溢出long long,要加个判断。
参考:http://blog.csdn.net/acm_baihuzi/article/details/49304911
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL INF = 1e18+10;
int nbln,nbun;
LL nbls[20],nbus[510];
LL low,high,nlcm;
LL __lcm(LL a, LL b)
{
if(a == -1 || b == -1) return -1;
LL tgcd = __gcd(a,b);
if(INF/b < a/tgcd) return-1;
return a/__gcd(a,b)*b;
}
LL solve(LL num)
{
LL ret = 0;
for(int i = 1; i < (1<<nbln); ++i)
{
LL mult = 1;
int cnt = 0;
for(int j = 0; j < nbln; ++j)
{
if(i&(1<<j))
{
++cnt;
mult = __lcm(mult,nbls[j]);
}
}
if(mult == -1) mult = INF;
LL tlcm = __lcm(nlcm,mult);
if(tlcm == -1) tlcm = INF;
if(cnt&1) ret += (num/mult - num/tlcm);
else ret -= (num/mult - num/tlcm);
}
return ret;
}
int main()
{
ios::sync_with_stdio(false);
while(cin >> nbln >> nbun >> low >> high)
{
if(nbln == 0 && nbun == 0 && low == 0 && high == 0) break;
nlcm = 1;
for(int i = 0; i < nbln; ++i)
cin >> nbls[i];
for(int i = 0; i < nbun; ++i)
{
cin >> nbus[i];
nlcm = __lcm(nlcm,nbus[i]);
}
cout << solve(high)-solve(low-1) <<endl;
}
return 0;
}