题目描述:计算(a,b)内能被7整除且不满足给定条件的数有多少个。
首先找出能被7整除的数,再除去能被7整除且满足一个条件的数,这可能会把满足两个条件的数减去两次,所以要加上即为容斥定理。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define ll long long
const int maxn=20;
ll p[maxn];
ll a[maxn];
ll M;int n;
bool vis[maxn];
ll mul_mod(ll a,ll b){
ll ans=0;
a%=M,b%=M;
while(b){
if(b&1)ans=(ans+a)%M;
b>>=1;
a=(a<<1)%M;
}
return ans;
}
void gcd(ll a,ll b,ll &d,ll &x,ll& y){
if(!b){d=a;x=1;y=0;}
else {gcd(b,a%b,d,y,x);y-=x*(a/b);}
}
ll china(int n,ll *a,ll *m){
M=1;
ll d,y,x=0;
for(int i=0;i<n;i++)if(vis[i])M*=m[i];
for(int i=0;i<n;i++)if(vis[i]){
ll w=M/m[i];
gcd(m[i],w,d,d,y);
x=(x+mul_mod(mul_mod(y,w),a[i]))%M;
}
return (x+M)%M;
}
int main()
{
int t;
ll x,y;
scanf("%d",&t);
for(int kase=1;kase<=t;kase++){
scanf("%d %lld %lld",&n,&x,&y);
p[0]=7;a[0]=0;
for(int i=1;i<=n;i++){
scanf("%lld %lld",&p[i],&a[i]);
}
int st=1<<n;
int cot;
ll ans=0;
vis[0]=true;
for(int i=0;i<st;i++){
cot=0;
for(int j=1;j<=n;j++){
if((1<<(j-1))&i){vis[j]=true;cot++;}
else vis[j]=false;
}
ll k1,k2;
ll A=china(n+1,a,p);
if(A>y)continue;
k1=(x-A+M-1)/M;k2=(y-A)/M;
if(cot%2==0)ans+=k2-k1+1;
else ans-=k2-k1+1;
}
printf("Case #%d: %lld\n",kase,ans);
}
return 0;
}