The first triangle number to have over a thousand divisors

So this is the twelfth problem of Project Euler (I mean with a 1000 instead of a 500), and though the reasoning to get it right seems rather easy, it becomes puzzling when you make a little-hard-way program, run it, and watch it go blank for several looooooooong hours. So here’s the original description of the problem (register in Project Euler & keep you own record!):

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?

So… the hardest way to do it is by checking divisors up to the nth triangle number. We obviously know that doesn’t work and we’re so clever that we notice right away that a fine optimization would be to check up to n/2. Ok! So go and try doing it this way! You’ll only get valuable time wasted and you'll wait for hours for the naughty number to magically appear (I mean, it’s not that this was my case ¬¬). So, how to do it? I suggest looking for a pattern in the sequence of divisors. A hint is that all triangle numbers seem to have an even number of divisors (I haven’t proved this sentence and I don’t know if someone already has).

So, work it out and when you’re ready, check out the algorithm below to see how I did it (it’s a really short one! and it works fine with MAX=1000).
long long int t=28, c=0, i, j;
for(i=8; c<MAX; i++)
{
c=0;
t+=i;
for(j=2; j<=t/j; j++)
{
if(t%j==0) {c++;}
}
c=2*(c+1);
}

No comments:

Post a Comment