# WARNING: The text below provides a guidance for a Project Euler problem.

• If you pride yourself in tackling problems entirely on your own, you are encouraged to exit this post right now.

• If you are simply looking for a hint for the problem, please visit the »Project Euler’s official forum«. You may find some hints here, but if you don’t want your problem spoiled, scroll cautiously.

• If you are looking for a readily available copy/paste answer, you will not find it here. All of the code snippets in the post have been stripped of some crucial lines (these are clearly marked). It is my aim that anyone able to replicate the answer based on such snippets will have to understand the solution conceptually. At that point, by virtue of learning something new, I believe he deserves it anyway.

• Guidance for future problems will not be published before 100 people have solved the problem and there are at least two more recent problems.



### Expressing an integer as the sum of triangular numbers

The problem tasks us with computing the function $G(n)$ expressing the number of ordered ways to write $n$ as a sum of three triangular numbers. Triangular numbers are numbers of the form $T_k = \frac {k(k+1)} 2;\ k = 0, 1, 2, \dots$.

We can readily convert the problem into somehow better looking equivalent. We can see that expressing $n$ as a sum of three triangular numbers $n = T_x + T_y + T_z$ is equivalent to expressing $8n + 3$ as a sum of three odd positive squares:

We thus have $G(n) = r_3(8n + 3)$ where $r_k$ is the sum of (k) squares function (tweaked such that the order of squares matters).

To compute $r_3$ we will use its obvious relation to (a simpler) $r_2$. If we manage to compute $r_2$ fast enough, this will be sufficient for the problem constraints. $r_3(n) = \sum_{k = 1}^{\lfloor \sqrt n \rfloor} r_2(n - k^2)$

The formula for $r_2$ is standard enough to be found in most Number theory textbooks. Writing the prime factorization of $n$ as $n = 2^\gamma \prod_{p \equiv 1 \text{ mod } 4} p^{\alpha_p} \prod_{q \equiv 3 \text{ mod } 4} q^{\beta_q},$ we have

Notice that if $n \text{ mod } 4 = 3$ then necessarily some of the $\beta_q$ must be odd, which accounts for a speedup in our function. Also, we take advantage of the binary representation of numbers and use $% $ instead of $n \text{ mod } 4$.

For the value $n = 17526000000000$ as required by the problem, this is unfortunately way too slow. Luckily, some time of researching1 has brought fruit in form of the recurrence which is very suitable for the problem input. We modify the “sum_of_three_squares” function accordingly.

Altogether, the code runs in 5 seconds, where the prime sieving takes by far the most time.

1. Michael D. Hirschhorn and James A. Sellers. ON REPRESENTATIONS OF A NUMBER AS A SUM OF THREE TRIANGLES. Acta Arithmetica 77 (1996), 289 - 301