# Triangular, pentagonal, and hexagonal
#
# Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
#   Triangle    T_n = n(n + 1) / 2      1, 3, 6, 10, 15, ...
#   Pentagonal  P_n = n(3n - 1) / 2     1, 5, 12, 22, 35, ...
#   Hexagonal   H_n = n(2n - 1)         1, 6, 15, 28, 45, ...
# It can be verified that T_285 = P_165 = H_143 = 40755.
#
# Find the next triangle number that is also pentagonal and hexagonal.

import math;
import matplotlib.pyplot;
import numpy;
import time;

start_time = time.time();

def t_n(n):
    return n * (n + 1) / 2;

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

def n_p(p):
    n = int((1 + round(math.sqrt(1 + (24 * p)))) / 6);
    if p == p_n(n):
        return n;
    else:
        return None;

def h_n(n):
    return n * ((2 * n) - 1);

def n_h(h):
    n = int((1 + round(math.sqrt(1 + (8 * h)))) / 4);
    if h == h_n(n):
        return n;
    else:
        return None;

def plot_t_n():
    x = numpy.linspace(-100, 100);
    matplotlib.pyplot.plot(x, t_n(x), '-', color = 'r');
    matplotlib.pyplot.show();

found = 0;
n = 285;
while True:
    t = t_n(n);
    arg_p = n_p(t);
    arg_h = n_h(t);
    if (arg_p != None) and (arg_h != None):
        print "%d = t_n(%d) = p_n(%d) = h_n(%d)" % (t, n, arg_p, arg_h);
        found += 1;
        if found >= 2:
            break;
    n += 1;

print "Execution time = %f seconds." % (time.time() - start_time);
