http://acm.hdu.edu.cn/showproblem.php?pid=4135
题目
求在区间 [ l , r ] 之间有多少个数与 n 互质
题解
- 相对于互质,不互质的数更好求
- 只要求出n的质因数,再看看 [ l , r ] 有多少个数含有这些因子
- 这时就需要一些容斥原理,奇加偶减
#include<bits/stdc++.h>
using namespace std;
int vis[1000010],cnt,tot;
long long p[1000010],a[1000010];
void sol(long long x)
{
tot=0;
for(int i=1; p[i]*p[i]<=x&&i<=cnt; i++)
{
if(x%p[i]==0)
{
a[++tot]=p[i];
while(x%p[i]==0) x=x/p[i];
}
}
if(x>1) a[++tot]=x;
}
long long print(long long x)
{
long long ans=0,i,s,t,j;
for(i=1; i<(1ll<<tot); i++)
{
s=0;
t=1;
for(j=1; j<=tot; j++)
{
if(i&(1ll<<(j-1)))
{
s++;
t=t*a[j];
}
}
if(s&1) ans+=x/t;
else ans-=x/t;
}
return ans;
}
int main()
{
freopen("a.txt","r",stdin);
long long t,tt,i,l,r,n,j;
scanf("%lld",&tt);
cnt=0;
tot=0;
memset(vis,0,sizeof(vis));
for(i=2; i<1000010; i++)
{
if(vis[i]==0)
{
p[++cnt]=i;
for(j=i*i; j<1000010; j+=i) vis[j]=1;
}
}
for(t=1; t<=tt; t++)
{
scanf("%lld%lld%lld",&l,&r,&n);
sol(n);
printf("Case #%lld: %lld\n",t,r-print(r)-l+1+print(l-1));
}
return 0;
}