#!/usr/bin/env python

"""
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.
"""

# Generators that spit out incrementing numbers
def gen3():
    n=1
    while True:
        yield n*(n+1)/2
        n += 1
def gen5():
    n=1
    while True:
        yield n*(3*n-1)/2
        n += 1
def gen6():
    n=1
    while True:
        yield n * (2*n - 1)
        n += 1

# Loop over generators until they all agree on a number
if __name__ == '__main__':
    ti = gen3().__iter__()
    pi = gen5().__iter__()
    hi = gen6().__iter__()
    t = p = h = orig = 1
    current = 40756 # Starting point given in the problem description
    while current > orig:
        orig = current
        while t < current: t = ti.next()
        if t > current: current = t
        while p < current: p = pi.next()
        if p > current: current = p
        while h < current: h = hi.next()
        if h > current: current = h
    print current
