Search This Blog

Saturday, December 18, 2010

Euler Problem 28

Hmmm.. so a spiral… going out from the centre…

Well this isn’t the smoothest solution but I noticed the following from the example given:

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

the numbers from the 4 diagonals are:

1,9,25     1,3,13      1,5,17    1,7,21

So I added another lap around the square and found the intervals between numbers were:

1,9,25,49     1,3,13,31      1,5,17,37    1,7,21,43
8  16   24          2  10  18        4 12  20      6  14  22
   8   8               8   8              8   8            8   8 

Hmmmm.. so.. the first diagonal (1,9,25) just goes up in multiples of 8… and so do the others but from different starting points.

So I just made an app which cycled thru building the numbers for each diagonal and adding to a list.. then pull them in order from the list and calc the sum! The only thing to remember is that in the sum you should only count the 1 in the centre a single time.. so I just did a –3… found this out from testing it against their example of a 5x5 square.

Oh and the other thing is when to stop adding… so I just determined this by going until the max value in the first diagonal reached the square of the size…

Like I said.. a bit messy.. but got me the answer first time!

________

static void Main(string[] args)
       {
           int size=  1001;
           long d1 = 1;
           long d2 = 3;
           long d3 = 5;
           long d4 = 7;
           int i = 0;
           long offsetd2 = 2;
           long offsetd3 = 4;
           long offsetd4 = 6;

           List<long> l1 = new List<long>();
           List<long> l2 = new List<long>();
           List<long> l3 = new List<long>();
           List<long> l4 = new List<long>();

           l2.Add(1);
           l2.Add(3);
           l3.Add(1);
           l3.Add(5);
           l4.Add(1);
           l4.Add(7);

           while (d1<((size*size)+1))
           {
               offsetd2 += 8;
               offsetd3 += 8;
               offsetd4 += 8;

               d1 += 8 * i;
               d2 += offsetd2;
               d3 += offsetd3;
               d4 += offsetd4;

               l1.Add(d1);
               l2.Add(d2);
               l3.Add(d3);
               l4.Add(d4);

         
           i++;
           }

           //sort out starting positions

          long sum = 0;

           for (int w = 0; w < (i-1); w++)
           {
               sum += l1[w] + l2[w] + l3[w] + l4[w];
           }

           Console.WriteLine(sum-3);  //1 is only counted on one of the diagonals so -3 from total

            Console.ReadLine();

       }

No comments: