P2257 YY的GCD
思路
求∑i=nn∑j=1mgcd(i,j)==k(k∈prime)\sum_{i = n} ^{n} \sum_{j = 1} ^{m} gcd(i, j) == k (k \in prime)∑i=nn∑j=1mgcd(i,j)==k(k∈prime)
对上面式子进行化简:
=∑k=1n∑i=1nk∑j=1mkgcd(i,j)==1,k∈prime= \sum_{k = 1} ^{n} \sum_{i = 1} ^{\frac{n}{k}}\sum_{j = 1} ^{\frac{m}{k}}gcd(i, j) == 1, k \in prime=k=1∑ni=1∑knj=1∑kmgcd(i,j)==1,k∈prime
=∑k=1n∑i=1nk∑j=1mk∑d∣gcd(i,j)μ(d),k∈prime= \sum_{k = 1} ^{n} \sum_{i = 1} ^{\frac{n}{k}}\sum_{j = 1} ^{\frac{m}{k}}\sum_{d\mid gcd(i, j)}\mu(d) , k \in prime=k=1∑ni=1∑knj=1∑kmd∣gcd(i,j)∑μ(d),k∈prime
=∑k=1n∑d=1nkμ(d)nkdmkd,k∈prime= \sum_{k = 1} ^{n} \sum_{d = 1} ^{\frac{n}{k}} \mu(d) \frac{n}{kd}\frac{m}{kd} , k \in prime=k=1∑nd=1∑knμ(d)kdnkdm,k∈prime
我们另t=kdt = kdt=kd
=∑t=1nntmt∑k∣tμ(tk),k∈prime= \sum_{t = 1} ^{n}\frac{n}{t}\frac{m}{t}\sum_{k \mid t}\mu(\frac{t}{k}), k \in prime=t=1∑ntntmk∣t∑μ(kt),k∈prime
∑k∣tμ(tk),k∈prime\sum_{k \mid t}\mu(\frac{t}{k}), k \in prime∑k∣tμ(kt),k∈prime这一项我们显然可以通过类埃筛求得,之后我们只要对前面的进行除法分块即可。
代码
最后一个测试点刚好卡着时间过去的。
/*Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1using namespace std;typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x;
}const int N = 1e7 + 10;bool st[N];vector<int> prime;int mu[N], n, m;ll sum[N];void mobius() {st[0] = st[1] = mu[1] = 1;for(int i = 2; i < N; i++) {if(!st[i]) {prime.pb(i);mu[i] = -1;}for(int j = 0; j < prime.size() && i * prime[j] < N; j++) {st[i * prime[j]] = 1;if(i % prime[j] == 0) {mu[i * prime[j]] = 0;break;}mu[i * prime[j]] = -mu[i];}}for(int i = 0; i < prime.size(); i++) {for(int j = 1; prime[i] * j < N; j++) {sum[j * prime[i]] += mu[j];}}for(int i = 1; i < N; i++) sum[i] += sum[i - 1];
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);mobius();int T = read();while(T--) {n = read(), m = read();if(n > m) swap(n, m);ll ans = 0;for(ll l = 1, r; l <= n; l = r + 1) {r = min(n / (n / l), m / (m / l));ans += 1ll * (sum[r] - sum[l - 1]) * (n / l) * (m / l);}printf("%lld\n", ans);}return 0;
}