容斥原理 第三题 要注意求最小公倍数时会超 long long 的问题
代码:
#include<iostream> #include<cstring> #include<cstdio> #include<string> #include<set> #include<map> #include<cmath> #include<algorithm> #include<vector> #include<cmath> #include<queue> #include<stack> //#define ull unsigned long long #define ll long long using namespace std; const int INF=0x3f3f3f3f; const int MOD=1000000007; const ll LMOD=1000000007; const double eps=1e-6; const int N=1050; ll gcd(ll x,ll y) { if(x%y==0) return y; return gcd(y,x%y); } ll lcm(ll x,ll y) { return x*y/gcd(x,y); } ll solve(ll n,vector<int> &a) { ll sum=0; for(int k=1;k<(1<<(int)a.size());++k) { int num=0; ll LCM=1; for(int i=0;i<(int)a.size();++i) { if((k&(1<<i))>0) { ++num; LCM=lcm(LCM,(ll)a[i]); if(LCM>n) break; } } if(LCM>n) continue; if((num&1)>0) { sum+=(n/LCM); }else { sum-=(n/LCM); } } //cout<<sum<<endl; return sum; } class Divisibility { public: int numDivisible(int L, int R, vector <int> a) { return (int)(solve(R,a)-solve(L-1,a)); } };