题解:
容斥原理。补集转化:将问题转化为求1~x内与n不互质的数的个数。将n分解质因数后,答案为:是一个质因数的倍数的数的个数 - 是两个质因数的倍数的数的个数 + 是三个质因数的倍数的数的个数......
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll a,b,n,p[104];
int cnt;
inline ll query(ll x) {
ll ret=0;
for (ll i=1;i<(1<<cnt);++i) {
bool lim=0;
ll t=1;
for (int j=0;j<cnt;++j)
if (i&(1<<j)) t*=p[j],lim^=1;
if (lim) ret+=x/t;
else ret-=x/t;
}
return ret;
}
int main() {
int kase;
scanf("%d",&kase);
for (int cof=1;cof<=kase;++cof) {
cnt=0;
scanf("%lld%lld%lld",&a,&b,&n);
for (ll i=2;i*i<=n;++i) {
if (n%i==0) {
p[cnt++]=i;
while (n%i==0) n/=i;
}
}
if (n^1) p[cnt++]=n;
printf("Case #%d: %lld\n",cof,(ll)b-query(b)-(a-1-query(a-1)));
}
return 0;
}