--------------------------------------------------
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 13
It can be verified that the sum of both diagonals is 101.
What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?
--------------------------------------------------
C# brute-force solution:
static long SpiralDiagonalsSum(long spiralsize)
{
long sum = 1;
long cursize = 3;
long number = 1;
while (cursize <= spiralsize)
{
for (int i = 0; i < 4; i++)
{
number += cursize - 1;
sum += number;
}
cursize += 2;
}
return sum;
}
static void Main(string[]args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
long diagsum = SpiralDiagonalsSum(1001);
sw.Stop();
Console.WriteLine("Spiral diagonals sum {0} calculated in {1} ms", diagsum, sw.Elapsed.TotalMilliseconds);
Console.ReadLine();
}
Solution on core duo performs in a 0.2 ms.
No comments:
Post a Comment
Comment will be posted after comment moderation.
Thank you for your appreciation.