Search This Blog

Sunday, December 12, 2010

Euler–Project Number 12

http://projecteuler.net/index.php?section=problems&id=12

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

____________________________

Ok so this was a bit tricky… the dumb approach to just add up numbers and keep trying for factors takes WAY too long.. so you need to use the summation formula:

Sum of numbers up to n = n(n+1)/2

Then remember you only need to find half of the factors… so when factorising 12 you’d get:

1,2,3,4,6,12 – 1 and 12 are obvious so start with 2 factors…

then work your way up to sqrt(12) to get 2,3 as factors…
their counter parts will be 6,4 – but you don’t need to know them.. only that they exist.. so in other words just double up the number of factors found up to sqrt(12) = 4

So total number of factors for 12 is 2 + 4 = 6

________________

CODE:

static void Main(string[] args)
      {
          int t;
          int f = 0;

          for (int q = 2; q < 1000000000; q++)
          {
               //sum of all numbers up to t using summation formula
              t = q * (q + 1) / 2;
          //factors

              f = 2;  //1 and the number t to be added as factors
              for (int z = 2; z < (Math.Sqrt(t)+1); z++)
              {
                  if (t % z == 0) { f+=2; }

              }
         if (f >= 500)
          {
              Console.WriteLine(t +","+ f);
          }

          }

         Console.WriteLine(">>");

          Console.ReadLine();

      }

No comments: