TITLE: A way to simplify $\gcd(a,b)$ condition in a double sum?
QUESTION [5 upvotes]: I have
$$\sum_{{\Large 1 \leq a,b \leq L} \atop {\Large  \gcd(a,b)=1}}(L+1-a)(L+1-b)$$
Which means iterating $1 \le a \le L$ and $1 \le b \le L$ and only adding $(L+1-a)(L+1-b)$ to the sum if $a$ and $b$ are coprime.
Is there a faster way that is not $O(N^2)$? I know how to count how many coprime pairs there are under a limit but not how to take into account the $a$ and $b$ and how they contribute to the sum

REPLY [4 votes]: Well, you could simplify as follows:
\begin{align}
\sum_{{\Large 1 \leq a,b \leq L} \atop {\Large  \gcd(a,b)=1}}{(L+1-a)(L+1-b)}& =L^2+2 \cdot \left(\sum_{{\Large 1 \leq b<a \leq L} \atop {\Large  \gcd(a,b)=1}}{(L+1-a)(L+1-b)}\right) \\
& =L^2+2 \cdot \left(\sum_{\Large 2 \leq a \leq L}{(L+1-a)\sum_{{\Large 1 \leq b<a} \atop {\Large  \gcd(a,b)=1}}{(L+1-b)}}\right) \\
& =L^2+2 \cdot \left(\sum_{\Large 2 \leq a \leq L}{(L+1-a)\left((L+1)\varphi{(a)}-\frac{a\varphi{(a)}}{2}\right)}\right) \\
& =L^2+2\cdot \left(\sum_{\Large 2 \leq a \leq L}{(L+1-a)\left(L+1-\frac{a}{2}\right)\varphi{(a)}} \right)
\end{align}
Now you just need to sum over $a$. Is that fast enough for you?
Edit: One simple way to compute $\varphi{(a)}$ for $2 \leq a \leq L$ would be to recursively generate the Farey sequences $F_n$ up to $n=L$, and take difference of number of terms of successive sequences along the way: $|F_a|-|F_{a-1}|=\varphi{(a)}$