# pe45.py
import math
"""
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(3n1)/2	 	1, 5, 12, 22, 35, ...
Hexagonal	 	Hn=n(2n1)	 	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.
"""

"""
Plan:
Take Triangle numbers successively from T(285) and test if they are Pentagonal and
Hexagonal numbers.

All three types of numbers are defined by quadratic equations. Hence, if I take the n'th
triangle number I can test whether or not it is pentagonal or hexagonal by looking at the
roots of the corresponding quadratic equation. If the (positive) root is an integer then we
can infer that the given triangle number is also a pentagonal or hexagonal number.
"""

def Tri(n):
    return n*(n + 1) / 2

def Pent(n):
    return n * (3*n -1) / 2

def Hex(n):
    return n * (2*n - 1)
    

def solvePent(m):
    # n*(3n-1)/2 = m
    # 3n*n -n - 2m = 0
    #x = 1.0/6 + math.sqrt((1 + 4*3*2*m))/6.0
    c = abs(float(1 + 4*3*2*m))
    x =  c ** 0.5
    root1 = ((1 + x)/6.0)
    root2 = ((1 - x)/6.0)
    if root1 > 0:
        return root1
    else:
        return root2

def solveHex(m):
    # n * (2*n -1) = m
    # 2n*n -n -m = 0
    # x = 1.0/6 + sqrt(1 + 4*2*m)/4
    c = abs(float(1 + 4*2*m))
    x =  c ** 0.5
    root1 = ((1 + x)/4.0)
    root2 = ((1 - x)/4.0)
    if root1 > 0:
        return root1
    else:
        return root2

def isInt(n):
    if math.ceil(n)/n == 1 or math.floor(n) == 1:
        return 1
    else:
        return 0

print Tri(285)
print solvePent(40755)
print solveHex(Tri(285))


i = 286
while i < 1000000:
    c = Tri(i)
    d = solvePent(c)
    e = solveHex(c)
    if isInt(d) == 1 and isInt(e) ==1:
        print c
        break
    else:
        i += 1










