Sunday 12 April 2009

PROJECT EULER #28

Link to Project Euler problem 28

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?

using System;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 28
//for a n x n spiral, the corners are given by
//tr: n^2, tl: n^2 - n + 1, bl: n^2 - 2n + 2, br: n^2 - 3n + 3.
//so for each square we get 4n^2 - 6n + 6.
DateTime start = DateTime.Now;
int sum = 0;
for (int i = 3; i < 1002; i+=2)
{
sum += 4*i*i - 6*i + 6;
}
//The middle number (1) is counted twice ;-)
sum += 1;
Console.WriteLine(sum);
TimeSpan time = DateTime.Now-start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: