06.14.08
Project Euler: Problem 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?
A solution:
Below, the function prime_factors is given here.
from factor import prime_factors
from operator import mul
triangle_num = 3 # starting place: 1+2=3
max_factors = 2
to_add = 2
while max_factors <= 500:
to_add += 1
triangle_num += to_add
factors = prime_factors(triangle_num)
count = []
while len(factors) != 0:
count.append(factors.count(factors[0])) # how many of the first factor
del factors[:count[-1]] # take out all instances of first factor
# count is now a list of how many of each factor
# e.g. for 28 = 2*2*7, count = [2,1]
# number of all factors is then given by (2+1)*(1+1) because each factor
# will have the form (2**x)*(7**y) where x = 0 or 1 or 2, y = 0 or 1
not_just_prime_factors = reduce(mul, [count[i]+1
for i in range(len(count))])
max_factors = max(not_just_prime_factors, max_factors)
print triangle_num
print max_factors
