容斥原理
题意为输入a,b,n。找到区间[a,b]间与n互质的数的数量.
首先我们将n拆分成质因数.
利用容斥原理,答案就是b-a+1减去有奇数个质因子的数,加上有偶数个质因子的数.
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
__int64 rec[6000000],k,ans,a,b,n,N;
__int64 GCD(__int64 a,__int64 b)
{
__int64 t;
while(b)
{
t=a;
a=b;
b=t%b;
}
return a;
}
__int64 LCM(__int64 a,__int64 b)
{
return a/GCD(a,b)*b;
}
void dfs(__int64 p,__int64 co,__int64 sigh)//dfs(-1,1,1);
{
__int64 i;
if(p>=k)
return ;
if(p>=0)
ans+=sigh*(b/co-(a-1)/co);
for(i=p+1;i<k;i++)
dfs(i,LCM(co,rec[i]),-sigh);
}
int main()
{
__int64 t;
__int64 flag=1;
__int64 i,j;
scanf("%I64d",&t);
while(t--)
{
k=0;
scanf("%I64d%I64d%I64d",&a,&b,&n);
N=sqrt(n);
for(i=2;i<=N;i++)
if(n%i==0)
{
rec[k++]=i;
while(n%i==0)
{
n/=i;
}
}
if(n!=1)
{
rec[k++]=n;
}
ans=b-a+1;
dfs(-1,1,1);
printf("Case #%I64d: %I64d\n",flag++,ans);
}
return 0;
}