2010-05-04 18:21:07 +00:00
|
|
|
"""What is the value of the first triangle number to have over five hundred divisors?
|
|
|
|
|
|
|
|
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?
|
|
|
|
"""
|
|
|
|
|
2010-04-12 15:53:15 +00:00
|
|
|
from e003 import pfactor
|
|
|
|
from p054.poker import unique_combinations
|
|
|
|
|
|
|
|
def triangle(n):
|
|
|
|
x = 0
|
|
|
|
for i in range(n + 1):
|
|
|
|
x = x + i
|
|
|
|
return x
|
|
|
|
|
|
|
|
def badfactor(n):
|
|
|
|
f = []
|
|
|
|
for i in range(n, 0, -1):
|
|
|
|
if n % i == 0:
|
|
|
|
f.append(i)
|
|
|
|
return f
|
|
|
|
|
|
|
|
def product(l):
|
|
|
|
p = 1
|
|
|
|
for n in l:
|
|
|
|
p = p * n
|
|
|
|
return p
|
|
|
|
|
|
|
|
def factor(n):
|
|
|
|
primes = pfactor(n)
|
2010-04-12 15:53:16 +00:00
|
|
|
factors = [1, n]
|
2010-04-12 15:53:15 +00:00
|
|
|
pow = {}
|
|
|
|
for p in primes:
|
|
|
|
if p not in pow.keys():
|
|
|
|
pow[p] = 0
|
|
|
|
pow[p] = pow[p] + 1
|
|
|
|
factors.append(p**pow[p])
|
2010-04-12 15:53:16 +00:00
|
|
|
|
|
|
|
for p in [f for f in factors if f > 1]:
|
|
|
|
f = n / p
|
|
|
|
if f not in factors:
|
|
|
|
factors.append(n / p)
|
|
|
|
combos = unique_combinations(factors, 2)
|
|
|
|
for c in combos:
|
|
|
|
f = product(c)
|
|
|
|
if f < n and n % f == 0 and f not in factors:
|
|
|
|
factors.append(f)
|
2010-04-12 15:53:15 +00:00
|
|
|
|
|
|
|
if n not in factors:
|
|
|
|
factors.append(n)
|
|
|
|
|
|
|
|
return sorted(set(factors))
|
2010-05-04 18:21:07 +00:00
|
|
|
def main():
|
2010-04-12 15:53:15 +00:00
|
|
|
i = 1
|
|
|
|
while True:
|
|
|
|
i = i + 1
|
|
|
|
t = triangle(i)
|
|
|
|
f = factor(t)
|
2010-04-12 15:53:16 +00:00
|
|
|
print 'Checking triangle', i, t, len(f)
|
2010-04-12 15:53:15 +00:00
|
|
|
if len(f) > 500:
|
|
|
|
break
|
|
|
|
|
2010-05-04 18:21:07 +00:00
|
|
|
print 'Triangle number {0} has {1} factors ({2})'.format(t, len(f), f)
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|