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.
Naive solution.
One way is to choose from all 'pentagonal' numbers and check if it is triangle and hexagonal.
from math import sqrt, ceil
get_triangle = lambda n: n * (n+1) // 2
get_pentagonal = lambda n: n * (3*n-1) // 2
get_hexagonal = lambda n: n * (2*n-1)
def is_triangle(n):
return n == get_triangle(int(sqrt(2*n)))
is_triangle(10)
is_triangle(12)
def is_hexagonal(n):
return n == get_hexagonal(ceil(sqrt(n / 2)))
is_hexagonal(40755)
is_hexagonal(30)
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
solve()