Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
using System;
using System.Diagnostics;
using System.Linq;
namespace ProjectEuler_28
{
internal class Program
{
private static void Main(string[] args)
{
const int squareSize = 1001;
Stopwatch sw = Stopwatch.StartNew();
int half = (int)Math.Ceiling(squareSize / 2D) - 1;
int[] topRight = new int[half];
int[] topLeft = new int[half];
int[] bottomLeft = new int[half];
int[] bottomRight = new int[half];
int idx = 0;
for (int i = squareSize; i > 1;)
{
topRight[idx] = i * i;
topLeft[idx] = topRight[idx] - i + 1;
bottomLeft[idx] = topLeft[idx] - i + 1;
bottomRight[idx] = bottomLeft[idx] - i + 1;
i = (int)Math.Floor(Math.Sqrt(bottomRight[idx]));
idx++;
}
sw.Stop();
Console.WriteLine($"Sum of diagonols: {topRight.Sum() + topLeft.Sum() + bottomLeft.Sum() + bottomRight.Sum() + 1} in {sw.ElapsedTicks} ticks");
}
}
}