嘟嘟嘟
看到求区间的,一个很好的思路就是转换成前缀和相减。那么这道题就是二维前缀和。
容易列出
[sum _ {i = 1} ^ {n} sum _{j = 1} ^ {m} [gcd(i, j) = k]
]
然后就是套路的推导了,跟这道题一模一样,看我的题解吧[POI2007]ZAP-Queries。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e4 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n;
int a, b, c, d, k;
int prim[maxn], v[maxn], mu[maxn];
ll sum[maxn];
In void init()
{
mu[1] = 1;
for(int i = 2; i < maxn; ++i)
{
if(!v[i]) v[i] = i, prim[++prim[0]] = i, mu[i] = -1;
for(int j = 1; j <= prim[0] && prim[j] * i < maxn; ++j)
{
v[i * prim[j]] = prim[j];
if(i % prim[j] == 0)
{
mu[i * prim[j]] = 0;
break;
}
else mu[i * prim[j]] = -mu[i];
}
}
for(int i = 1; i < maxn; ++i) sum[i] = sum[i - 1] + mu[i];
}
In ll solve(int n, int m)
{
n /= k; m /= k;
if(n > m) swap(n, m);
ll ret = 0;
for(int l = 1, r; l <= n; l = r + 1)
{
r = min(n / (n / l), m / (m / l));
ret += (sum[r] - sum[l - 1]) * (n / l) * (m / l);
}
return ret;
}
int main()
{
init();
n = read();
for(int i = 1; i <= n; ++i)
{
a = read(), b = read(), c = read(), d = read(), k = read();
write(solve(b, d) - solve(b, c - 1) - solve(d, a - 1) + solve(a - 1, c - 1)), enter;
}
return 0;
}