link。
Denote cntx = the number of occurrences of x, h = the maximum of ai, there we get
1⩽i⩽n∑1⩽j⩽n∑[ai,aj]=1⩽d⩽h∑1⩽i⩽h∑1⩽j⩽h∑[(i,j)=d]×di×j×cnti×cntj=1⩽d⩽h∑d1⩽i⩽⌊dh⌋∑1⩽j⩽⌊dh⌋∑k∣(i,j)∑μ(k)×i×j×cntid×cntjd=1⩽d⩽h∑d1⩽k⩽⌊dh⌋∑μ(k)×k21⩽i⩽⌊dkh⌋∑1⩽j⩽⌊dkh⌋∑i×j×cntidk×cntjdk=1⩽T⩽h∑Tk∣T∑μ(k)×k1⩽i⩽⌊Th⌋∑i×cntiT1⩽j⩽⌊Th⌋∑j×cntjT
Denote f(T)=1⩽i⩽h/T∑i×cntiT, g(T)=1⩽i⩽h/T∑i×cntiT×f(T)
1⩽T⩽h∑Tk∣T∑μ(k)×k1⩽i⩽⌊Th⌋∑i×cntiT1⩽j⩽⌊Th⌋∑j×cntjT=1⩽T⩽h∑Tk∣T∑μ(k)×k×g(T)
Denote z(T)=Tk∣T∑μ(k)×k, the answer would be 1⩽i⩽h∑z(i)×g(i).
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define cmin(x, y) x = min(x, y)
#define cmax(x, y) x = max(x, y)
#define fors(i, l, r, ...) for(int i = (l), REP##i = (r), ##__VA_ARGS__; i <= REP##i; ++i)
#define dfors(i, r, l, ...) for(int i = (r), REP##i = (l), ##__VA_ARGS__; i >= REP##i; --i)
signed main() {
ios::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
for(int& x : a) cin >> x;
const int h = *max_element(a.begin(), a.end());
vector<int> cnt(h+1);
for(const int x : a) cnt[x]++;
const auto z = [](const int n) {
vector<int> mu(n+1), prime, not_prime(n+1);
vector<ll> z(n+1);
mu[1] = 1;
fors(i, 2, n) {
if(not_prime[i] == 0) prime.emplace_back(i),mu[i] = -1;
for(const int p : prime) {
if(i > n/p) break;
not_prime[i*p] = 1;
if(i%p == 0) break;
mu[i*p] = -mu[i];
}
}
fors(d, 1, n) {
for(int T = d; T <= n; T += d) z[T] += ll(mu[d])*d;
}
return z;
}(h);
ll ans = 0;
fors(i, 1, h) {
ll tmp = 0;
fors(j, 1, h/i) tmp += ll(cnt[i*j])*j;
ans += tmp*tmp*z[i]*i;
}
cout << ans << "\n";
return 0;
}