給定 A, B, N (1 ≤ A ≤ B ≤ 10^15, 1 ≤ N ≤ 10^9),求區間 [A, B] 中與 N 互質的整數個數。T ≤ 100 組測試。
N 的質因數:N = p1^e1 * p2^e2 * ... * pk^ek。只需質因數集合 {p1..pk},k ≤ 9(因 2×3×5×7×11×13×17×19×23 > 10^9)。N 互質 ⇔ 不被任何 pi 整除。[1, x] 中不被任一 pi 整除的數個數:f(x) = x - Σ(x/pi) + Σ(x/(pi*pj)) - ...。f(B) - f(A-1)。#include <bits/stdc++.h> using namespace std; using LL = long long; LL A, B, N; vectorprimes; void factorize(LL n) { primes.clear(); for (LL p = 2; p * p <= n; ++p) { if (n % p == 0) { primes.push_back(p); while (n % p == 0) n /= p; } } if (n > 1) primes.push_back(n); } LL count_coprime(LL x) { // [1, x] 中與 N 互質的數 if (x <= 0) return 0; LL res = x; int k = primes.size(); for (int mask = 1; mask < (1< > T; for (int cas = 1; cas <= T; ++cas) { cin >> A >> B >> N; factorize(N); LL ans = count_coprime(B) - count_coprime(A - 1); cout << "Case #" << cas << ": " << ans << '\n'; } return 0; }
A, B 達 10^15,必須用 64 位整數(long long)。count_coprime(0) 返回 0,處理 A=1 邊界。