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?
A problem of 'factor decomposition'
Brute force.
def decompose(number):
factors = [1, number]
d = 2
while pow(d, 2) < number:
if number % d == 0:
factors.extend([d, number // d])
d += 1
return factors
decompose(28)
def generate_triangle_number():
i = 1
while True:
yield i * (i + 1) // 2
i += 1
def solve(divisor_number):
for triangle_number in generate_triangle_number():
# result triangle number must greater than pow(divisor_number, 2)
if triangle_number < pow(divisor_number, 2):
continue
if len(decompose(triangle_number)) > divisor_number:
return triangle_number
solve(5)
solve(500)