-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp045.py
46 lines (37 loc) · 1.28 KB
/
p045.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'''
Triangle, pentagonal, and hexagonal numbers are generated by the following
formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n-1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n-1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
'''
import common
import itertools
def triangles():
for n in itertools.count(1):
yield n*(n+1)/2
common.assertEquals([1, 3, 6, 10, 15], list(itertools.islice(triangles(), 5)))
def pentagons():
for n in itertools.count(1):
yield n*(3*n-1)/2
common.assertEquals([1, 5, 12, 22, 35], list(itertools.islice(pentagons(), 5)))
def hexagons():
for n in itertools.count(1):
yield n*(2*n-1)
common.assertEquals([1, 6, 15, 28, 45], list(itertools.islice(hexagons(), 5)))
def tripentahexas():
ts, ps, hs = triangles(), pentagons(), hexagons()
t, p, h = ts.next(), ps.next(), hs.next()
while True:
if t < p or t < h: t = ts.next()
elif p < t or p < h: p = ps.next()
elif h < t or h < p: h = hs.next()
else:
yield t
t, p, h = ts.next(), ps.next(), hs.next()
tphs = tripentahexas()
common.assertEquals(1, tphs.next())
common.assertEquals(40755, tphs.next())
common.submit(tphs.next(), expected=1533776805)