I want to find the sum of LCM of a given range of integers. For example:
Input: $5$
Output:
\begin{align} \sum_{i=1}^5 \mathrm{LCM}(i,5) & = \mathrm{LCM}(1,5) +\mathrm{LCM}(2,5) +\mathrm{LCM}(3,5) + \mathrm{LCM}(4,5) + \mathrm{LCM}(5,5) \\ & = 5 + 10 + 15 + 20 + 5 \\ & = 55 \end{align}
The method I use right now is to find the $\mathrm{GCD}(a,b)$ using Euclidean method and them compute $\mathrm{LCM}(a,n)$ as $\frac{|ab|}{\mathrm{GCD}(a,b)}$. The problem with this method is that it's very slow for inputs in the range of $1 < n < 10^5$.
I got some details of using Euler's totient function to do the same but I don't understand it completely.The one property which I understood is a $\phi(p) = p-1$ where $p$ is prime and I couldn't understand how to use this to improve the speed of my problem.The current algorithm which I use runs at $O(n^2)$ and I need to do better than that.
You may speed it up a bit by making only 1 multiplication:
$$\sum_{i=1}^n\text{lcm}(i,n)=\sum_{i=1}^n\frac{i n}{\gcd(i,n)}=n\sum_{i=1}^n\frac{i}{\gcd(i,n)}$$
Since $i$ is divisible by $\gcd(i,n)$ that can be computed using only integer arithmetic. This has $O(n*log(n))$ complexity but is in constant factor faster than naive solution (2nd formula).