The following is my python solution of project euler 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,28We 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?
It works fine and runs in half second. I fixed a random upper limit for the search of primes (using the sieve of eratosthenes).
def SE(n): #Sieve of Eratosthenes
sieve = range(3, n, 2)
top = len(sieve)
for si in sieve:
if si:
bottom = (si*si - 3)/2
if bottom >= top:
break
sieve[bottom::si] = [0] * -((bottom-top)//si)
return [2] + filter(None, sieve)
primes = SE(13000) #Here's the problem
def nod(n): #function that returns the number of divisors
nd = 1
for i in primes:
if i <= n:
t = 1
while n % i == 0:
n /= i
t += 1
nd *= t
else:
return nd
c = 0
i = 1
d = 1
d1 = 0
while c < 500: #loop for checking each triangle number
if i % 2 == 0:
d = nod(i+1)
else:
d1 = nod((i+1)/2)
c = d * d1
i += 1
print i*(i-1)/2