题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=4135
题目意思:给定两个数 a b和一个数 n 求[a,b]范围内与n互素的数的个数
思路:我们可以用容斥计算出[1,B]之间和[1,A-1]之间的与N互质的数,然后相减即可。然后我们用一种快速的方法求出[1,X]之间的与N互质的数,首先我们求出N的质因子,[1,X]之间与N的质因子成倍数关系的数肯定与N不成互质关系。
code:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
#define maxn 100000
ll p[maxn];
int len;
ll a,b,n;
void init(ll n)//分解质因数
{
len=0;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
p[len++]=i;
while(n%i==0)
n/=i;
}
}
if(n>1)
p[len++]=n;
}
ll solve(ll n)
{
ll y=(ll)(1<<len);//情况的数量为y-1
ll res=0;
for(int i=1;i<y;i++)
{
ll flag=0;
ll temp=1;
for(int j=0;j<len;j++)
if(i&(ll)(1<<j))
{
flag++;
temp*=p[j];
}
if(flag&1)
res+=n/temp;
else res-=n/temp;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
int T;
cin>>T;
int kcas=1;
while(T--)
{
cin>>a>>b>>n;
init(n);
ll ans=(b-solve(b))-(a-1-solve(a-1));
cout<<"Case #"<<kcas++<<": "<<ans<<endl;
}
return 0;
}