题面
Description
对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。
Input
第一行一个整数n,接下来n行每行五个整数,分别表示a、b、c、d、k
Output
共n行,每行一个整数表示满足要求的数对(x,y)的个数
Sample Input
2
2 5 1 5 1
1 5 1 5 2
Sample Output
14
3
HINT
100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000
题解
所求即为 ∑ i = a b ∑ j = c d [ g c d ( i , j ) = k ] \sum _{i=a} ^b \sum _{j=c} ^d [gcd (i, j) = k] ∑i=ab∑j=cd[gcd(i,j)=k]
设 f ( n , m ) = ∑ i = 1 n ∑ j = 1 m [ g c d ( i , j ) = k ] f(n, m) = \sum _{i=1} ^n \sum _{j=1} ^m [gcd (i, j) = k] f(n,m)=∑i=1n∑j=1m[gcd(i,j)=k]
则 a n s = f ( b , d ) − f ( a − 1 , d ) − f ( b , c − 1 ) + f ( a − 1 , c − 1 ) ans = f (b, d) - f (a - 1, d) - f (b, c - 1) + f (a - 1, c - 1) ans=f(b,d)−f(a−1,d)−f(b,c−1)+f(a−1,c−1)
f ( n , m ) = ∑ i = 1 ⌊ n k ⌋ ∑ j = 1 ⌊ m k ⌋ [ g c d ( i , j ) = 1 ] f (n, m) = \sum _{i=1} ^{\lfloor \frac n k \rfloor} \sum _{j=1} ^{\lfloor \frac m k \rfloor} [gcd (i, j) = 1] f(n,m)=∑i=1⌊kn⌋∑j=1⌊km⌋[gcd(i,j)=1]
令 x = ⌊ n k ⌋ x = \lfloor \frac n k \rfloor x=⌊kn⌋, y = ⌊ m k ⌋ y = \lfloor \frac m k \rfloor y=⌊km⌋
莫比乌斯反演后得: f ( n , m ) = ∑ i = 1 x μ ( i ) ⋅ ⌊ x i ⌋ ⌊ y i ⌋ f(n, m) = \sum _{i=1} ^x \mu (i) \cdot \lfloor \frac x i \rfloor \lfloor \frac y i \rfloor f(n,m)=∑i=1xμ(i)⋅⌊ix⌋⌊iy⌋
数论分块。单次询问复杂度 O ( n ) O (\sqrt n) O(n),总复杂度 O ( T n ) O (T \sqrt n) O(Tn),其中 T T T为数据组数。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll ;
const int maxn = 5e4 + 10 ;
int mu[maxn], prime[maxn], tot ;
bool vis[maxn] ;
void init() {
mu[1] = 1 ;
for (int i = 2; i < maxn; i ++) {
if (!vis[i]) prime[++ tot] = i, mu[i] = -1 ;
for (int j = 1; j <= tot && i * prime[j] < maxn; j ++) {
vis[i * prime[j]] = 1;
if (i % prime[j] == 0) {
mu[i * prime[j]] = 0; break ;
}
mu[i * prime[j]] = -mu[i] ;
}
}
for (int i = 1; i < maxn; i ++) mu[i] += mu[i - 1] ;
}
inline int cal (int x, int y) {
if (x > y) swap (x, y) ;
int res = 0 ;
for (int i = 1, nxt = 0; i <= x; i = nxt + 1) {
nxt = min (x / (x / i), y / (y / i)) ;
res += (x / i) * (y / i) * (mu[nxt] - mu[i - 1]) ;
}
return res ;
}
int main() {
init () ;
int T ;
cin >> T ;
while (T --) {
int a, b, c, d, k ;
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k) ;
printf("%d\n", cal (b / k, d / k) - cal (b / k, (c - 1) / k) - cal ((a - 1) / k, d / k) + cal ((a - 1) / k, (c - 1) / k)) ;
}
return 0 ;
}