P1447 [NOI2010]能量采集
式子化简
显然题目就是要我们求∑i=1n∑j=1m2gcd(i,j)−1\sum_{i = 1} ^{n} \sum_{j = 1} ^{m} 2gcd(i, j) - 1∑i=1n∑j=1m2gcd(i,j)−1
=2∑i=1n∑j=1mgcd(i,j)−nm= 2\sum_{i = 1} ^{n} \sum_{j = 1} ^{m} gcd(i, j) - nm=2i=1∑nj=1∑mgcd(i,j)−nm
转化为我们要求∑i=1n∑j=1mgcd(i,j)\sum_{i = 1} ^{n} \sum_{j = 1} ^{m} gcd(i, j)∑i=1n∑j=1mgcd(i,j)
=∑d=1nd∑i=1nd∑j=1mdgcd(i,j)==1= \sum_{d = 1} ^{n}d\sum_{i = 1} ^{\frac{n}{d}} \sum_{j = 1} ^{\frac{m}{d}} gcd(i, j) == 1=d=1∑ndi=1∑dnj=1∑dmgcd(i,j)==1
套上mobiusmobiusmobius
=∑d=1nd∑i=1nd∑j=1md∑k∣gcd(i,j)μ(k)= \sum_{d = 1} ^{n}d\sum_{i = 1} ^{\frac{n}{d}} \sum_{j = 1} ^{\frac{m}{d}} \sum_{k \mid gcd(i, j)} \mu(k)=d=1∑ndi=1∑dnj=1∑dmk∣gcd(i,j)∑μ(k)
=∑d=1nd∑i=1nd∑j=1md∑k∣gcd(i,j)μ(k)= \sum_{d = 1} ^{n}d\sum_{i = 1} ^{\frac{n}{d}} \sum_{j = 1} ^{\frac{m}{d}} \sum_{k \mid gcd(i, j)} \mu(k)=d=1∑ndi=1∑dnj=1∑dmk∣gcd(i,j)∑μ(k)
=∑d=1nd∑k=1ndμ(k)⌊ndk⌋⌊mdk⌋= \sum_{d = 1} ^{n} d\sum_{k = 1} ^{\frac{n}{d}}\mu(k) \lfloor\frac{n}{dk}\rfloor \lfloor\frac{m}{dk}\rfloor=d=1∑ndk=1∑dnμ(k)⌊dkn⌋⌊dkm⌋
另t=dkt = dkt=dk
=∑t=1n⌊nt⌋⌊mt⌋∑d∣tdμ(td)= \sum_{t = 1} ^{n} \lfloor\frac{n}{t}\rfloor \lfloor\frac{m}{t}\rfloor \sum_{d \mid t}d\mu(\frac{t}{d})=t=1∑n⌊tn⌋⌊tm⌋d∣t∑dμ(dt)
mobiusmobiusmobius反演有∑d∣nμ(d)d=ϕ(n)n\sum_{d\mid n}\frac{\mu(d)}{d} = \frac{\phi(n)}{n}∑d∣ndμ(d)=nϕ(n)
=∑t=1n⌊nt⌋⌊mt⌋ϕ(t)= \sum_{t = 1} ^{n} \lfloor\frac{n}{t}\rfloor \lfloor\frac{m}{t}\rfloor \phi(t)=t=1∑n⌊tn⌋⌊tm⌋ϕ(t)
代码
/*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 n, m;ll phi[N];void mobius() {st[0] = st[1] = phi[1] = 1;for(int i = 2; i < N; i++) {if(!st[i]) {prime.pb(i);phi[i] = i - 1;}for(int j = 0; j < prime.size() && i * prime[j] < N; j++) {st[i * prime[j]] = 1;if(i % prime[j] == 0) {phi[i * prime[j]] = phi[i] * prime[j];break;}phi[i * prime[j]] = phi[i] * (prime[j] - 1);}}for(int i = 1; i < N; i++) phi[i] += phi[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();ll 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 += (n / l) * (m / l) * (phi[r] - phi[l - 1]);}printf("%lld\n", 2 * ans - n * m);return 0;
}