Problem 556
Sum of GCD over All Pairs
Hard · 30 pts · Math, Number Theory, Sieve
Problem
Compute the sum of gcd(i, j) over all pairs 1 <= i < j <= N. A double loop is far too slow for N = 1000000. Group the pairs by their gcd instead: for a fixed j, the number of i < j with gcd(i, j) = d equals φ(j / d) whenever d is a proper divisor of j. So the answer is the sum of d × φ(k) over all d >= 1 and k >= 2 with d × k <= N, which a totient sieve plus a harmonic loop computes in O(N log N). The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
A single integer N.
Output
Print the sum of gcd(i, j) over all pairs i < j.
Constraints
1 <= N <= 1000000
Example input
4
Example output
7
Explanation
For N = 4 the pairs give gcd(1,2) = 1, gcd(1,3) = 1, gcd(1,4) = 1, gcd(2,3) = 1, gcd(2,4) = 2 and gcd(3,4) = 1. Their sum is 7.