LCM Sum
Explicación
Usaremos la siguiente identidad para llevar la suma dada a una forma más conveniente:
Intentamos agrupar los términos por su valor. Sea , entonces :
Sea y ; de esto se obtiene que . Sustituyendo de vuelta en obtenemos:
La suma interior es igual a para .
Implementación
Complejidad temporal:
#include <iostream>
using namespace std;
const int MAXN = 1e6;
long long phi[MAXN + 1], sum[MAXN + 1];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
for (int i = 1; i <= MAXN; i++) { phi[i] = i; }
for (int i = 2; i <= MAXN; i++) {
// Si i es primo
if (phi[i] == i) {
for (int j = i; j <= MAXN; j += i) { phi[j] -= phi[j] / i; }
}
}
for (int i = 1; i <= MAXN; i++) {
for (int j = i; j <= MAXN; j += i) { sum[j] += i * phi[i]; }
}
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
long long ans = sum[n] + 1;
ans = 1LL * ans * n / 2LL;
cout << ans << '\n';
}
return 0;
}