1188 最大公约数之和 V2
思路
用欧拉函数可以化简式子如下
∑i=1n∑j=1i−1gcd(i,j)\sum_{i = 1} ^{n} \sum _{j = 1} ^{i - 1} gcd(i, j)i=1∑nj=1∑i−1gcd(i,j)
=∑i=1n∑j=1igcd(i,j)−(n+1)(n)2= \sum_{i = 1} ^{n} \sum_{j = 1} ^{i} \gcd(i, j) - \frac{(n + 1)(n)}{2}=i=1∑nj=1∑igcd(i,j)−2(n+1)(n)
=∑i=1n∑d∣id∑j=1i(gcd(i,d)==d)−(n+1)(n)2= \sum_{i = 1} ^{n} \sum_{d \mid i} d\sum_{j = 1}^{i}(gcd(i, d) == d) - \frac{(n + 1)(n)}{2}=i=1∑nd∣i∑dj=1∑i(gcd(i,d)==d)−2(n+1)(n)
=∑i=1n∑d∣idϕ(id)−(n+1)(n)2= \sum_{i = 1} ^{n} \sum_{d\mid i}d\phi(\frac{i}{d}) - \frac{(n + 1)(n)}{2}=i=1∑nd∣i∑dϕ(di)−2(n+1)(n)
我们再通过类似于埃筛来求得∑i=1n∑d∣idϕ(id)\sum_{i = 1} ^{n} \sum_{d\mid i}d\phi(\frac{i}{d})∑i=1n∑d∣idϕ(di),接下来就可以直接输出答案了。
代码
/*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 x = 0, f = 1; 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 x * f;
}const int N = 5e6 + 10;int phi[N], n;bool st[N];vector<int> prime;ll ans[N];void init() {st[0] = st[1] = 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]) {phi[i * prime[j]] = phi[i] * (prime[j] - 1);}else {phi[i * prime[j]] = phi[i] * prime[j];break;}}}for(int i = 1; i < N; i++) {for(int j = i; j < N; j += i) {ans[j] += 1ll * i * phi[j / i];}}for(int i = 1; i < N; i++) ans[i] += ans[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);init();int T;cin >> T;while(T--) {int n;cin >> n;cout << ans[n] - 1ll * (n + 1) * n / 2 << endl;}return 0;
}