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} & 22 & 23 & 24 & \color{red}{25} \\ 20 & \color{red}{7} & 8 & \color{red}{9} & 10 \\ 19 & 6 & \color{red}{1} & 2 & 11 \\ 18 & \color{red}{5} & 4 & \color{red}{3} & 12 \\ \color{red}{17} & 16 & 15 & 14 & \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);
}
}