题意:给你a,b,n,问区间[a, b]内有多少数与n互素?
解题思路:问题可以转化为求1到b内与n互素的个数减去1到a-1内与n互素的问题,那么现在的问题就是求1到x内与n互素的个数。要求1到x内与n互素的个数,可以先求不与n互素的个数。不与n互素的个数可以将n质因数分解,n的质因子的倍数肯定不与n互素。
例如x = 15, n = 10。n的质因子有2、5.。(2、4、6、8、10、12、14)->15/2 = 7 (5 、10、15)->15/5 = 3。考虑到其中有重复的,我们用容斥定理
15/2 + 15/5 - 15/(2*5) = 9。所以不与n互质的有9个,那么与n互质的有6个。
#include<cstdio>
#include<set>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e6 + 20;
const double EPS = 1e-5;
const int mod = 1e8 + 7;
typedef unsigned long long ull;
typedef long long LL;
int dx[] = {0, 0, -1, 1, -1, -1, 1, 1};
int dy[] = {1, -1, 0, 0, -1, 1, -1, 1};
long long a, b, n;
int num[maxn];
int cnt;
void init(){
cnt = 0;
int s = n;
for(int i = 2; i * i <= n; ++i){
if(s % i == 0){
num[cnt++] = i;
while(s % i == 0) s /= i;
}
}
if(s > 1) num[cnt++] = s;
}
long long solve(long long x){
long long ans = 0;
// printf("%d\n", cnt);
for(int i = 1; i < (1 << cnt); ++i){
int sum = 1;
int k = 0;
for(int j = 0; j < cnt; ++j){
if((1 << j) & i){
sum *= num[j];
k++;
}
}
if(k & 1) ans += x / sum;
else ans -= x / sum;
}
return x - ans;
}
int main(){
int T, kase = 0;
scanf("%d", &T);
while(T--){
scanf("%lld%lld%lld", &a, &b, &n);
init();
printf("Case #%d: %lld\n", ++kase, solve(b) - solve(a - 1));
}
}