Project Euler 28: sum of spiral diagonals using recursion I've solved Project Euler #28 using recursion.


  If this 5 × 5 spiral pattern is extended to 1001 × 1001, what would be the sum of the red diagonals?
  
  $$\begin{matrix}
\color{red}{21} &amp; 22 &amp; 23 &amp; 24 &amp; \color{red}{25} \\
20 &amp;  \color{red}{7} &amp;  8 &amp;  \color{red}{9} &amp; 10 \\
19 &amp;  6 &amp;  \color{red}{1} &amp;  2 &amp; 11 \\
18 &amp;  \color{red}{5} &amp;  4 &amp;  \color{red}{3} &amp; 12 \\
\color{red}{17} &amp; 16 &amp; 15 &amp; 14 &amp; \color{red}{13}
\end{matrix}$$


Is this a good enough solution, or is there some other way to optimize the code?

static long GetSumofDiagonals(int cubeSize)
    {
        long sum = 0;
        if (cubeSize == 1)
            return 1;
        else
        {
            // As the diagonal numbers follows a sequence
            // UR = n^2 - 1;
            // UL = UR - (n - 1)
            // LL = UL - (n -1 )
            // LR = LL - (n - 1)
            // This works only for odd n
            long UpperRight = (long) Math.Pow(cubeSize, 2);
            long UpperLeft = UpperRight - (cubeSize - 1);
            long LowerLeft = UpperLeft - (cubeSize - 1) ;
            long LowerRight = LowerLeft - (cubeSize - 1);
            sum = UpperRight + UpperLeft + LowerLeft + LowerRight;
            return sum + GetSumofDiagonals(cubeSize - 2);
        }
    }
Performance is okay (linear), but I think the code can be simplified by using a loop instead of recursion, and by going from the inside-out instead of from the outside-in.

Here's how I did it, in pseudo-code:

sum = 1   # running sum
last = 1  # last number
delta = 2 # delta between numbers

for layer in 1 to (sidelength - 1) / 2:
    for num in 1 to 4:
        last += delta
        sum += last
    delta += 2 # increases by two with each layer

return sum


Also, I think this is one of those probems that can actually be calculated directly using pencil and paper, without any loops. Why don't you check out the problem forum there?