Triangular, pentagonal, and hexagonal

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.


Idea

Naive solution.

One way is to choose from all 'pentagonal' numbers and check if it is triangle and hexagonal.


In [1]:
from math import sqrt, ceil
In [2]:
get_triangle = lambda n: n * (n+1) // 2
In [3]:
get_pentagonal = lambda n: n * (3*n-1) // 2
In [4]:
get_hexagonal = lambda n: n * (2*n-1)
In [5]:
def is_triangle(n):
    return n == get_triangle(int(sqrt(2*n)))
In [6]:
is_triangle(10)
Out[6]:
True
In [7]:
is_triangle(12)
Out[7]:
False
In [8]:
def is_hexagonal(n):
    return n == get_hexagonal(ceil(sqrt(n / 2)))
In [9]:
is_hexagonal(40755)
Out[9]:
True
In [10]:
is_hexagonal(30)
Out[10]:
False
In [11]:
def solve():
    pentagonal_ith = 1
    result = []
    while len(result) < 3:
        pentagonal = get_pentagonal(pentagonal_ith)
        if is_triangle(pentagonal) and is_hexagonal(pentagonal):
            result.append(pentagonal)
        pentagonal_ith += 1
    return result
In [12]:
solve()
Out[12]:
[1, 40755, 1533776805]