Problem 12 "Advanced Divisibility Triangular Number"
The sequence of triangular numbers is represented by the sum of natural numbers, the 7th triangular number is 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first 10 terms of the triangular number are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Becomes. The divisors of the first 7 terms are listed below.
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
From this we can see that the 7th triangular number 28 is the first triangular number with more than 5 divisors. Then, some of the first triangular numbers have divisors more than 500.
Python
import math
# limit = 5
limit = 500
def compute_factors(num):
factors = [1]
if(num == 1): return factors
for i in range(2, int(math.floor(math.sqrt(num))) + 1):
if(num % i == 0):
factors.append(i)
factors_rev = list(factors)
factors_rev.reverse()
for i in factors_rev:
fac = num // i
if(fac not in factors):
factors.append(fac)
return factors
triangular_nums = [1]
factors = []
n = 2
while True:
triangular_num = triangular_nums[n-1-1] + n
triangular_nums.append(triangular_num)
factors = compute_factors(triangular_num)
if(len(factors) > limit):
break
n += 1
result = triangular_nums[-1]
print result
print result == 76576500
print n
print factors[:10]
result
76576500
True
12375
[1, 2, 3, 4, 5, 6, 7, 9, 10, 11]
Recommended Posts