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?
def tri_num(num):
tri = 0
for x in xrange(1, num):
tri += x
yield tri
tri_list = [i for i in tri_num(10000)]
def find_factors(lst):
for i in xrange(len(lst)):
num_factors = 0
for x in xrange(1, lst[i]):
if lst[i]%x == 0:
num_factors += 1
if num_factors >= 500:
return lst[i]
print "range too small"
find_factors(tri_list)
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) <ipython-input-25-68c81c2995eb> in <module>() ----> 1 find_factors(tri_list) <ipython-input-24-ba9584544721> in find_factors(lst) 4 num_factors = 0 5 for x in xrange(1, lst[i]): ----> 6 if lst[i]%x == 0: 7 num_factors += 1 8 if num_factors >= 500: KeyboardInterrupt:
The above method is too slow. A more efficient method is needed.
import math
def factors2(num):
divisors = 0
square = int(math.sqrt(num))
for i in xrange(1, square):
if num % i == 0:
divisors += 2
if square * square == num:
divisors -= 1
return divisors
num = 0
x = 1
while(factors2(num) < 500):
num += x
x += 1
print num
76576500