Project Euler 45 Solution: Triangular, pentagonal, and hexagonal

Problem 45

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

TriangleTn=n(n+1)/21, 3, 6, 10, 15, ...
PentagonalPn=n(3n−1)/21, 5, 12, 22, 35, ...
HexagonalHn=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.


It's obvious that the set of hexagonal numbers is a subset of triangle numbers, i.e. we can substitute \(n=2m-1\) into the triangle number equation and get the hexagonal numbers equation:

\[\begin{array}{rl} T_n &= \frac{1}{2}n(n+1) \\ &= \frac{1}{2}(2m-1)((2m-1)+1) \\ &= (2m-1)m \\&= 2m^2-m\end{array}\]

That means that all triangular numbers which are generated with an odd \(n\) will be a hexagonal number. All we need to do is generating hexagonal numbers this way and check if they are a pentagonal number. Starting with the smallest hexagonal number, which we already know and using the quite optimized pentagonal number check from Problem 44 allows us to come up with the following implementation:

function solution() {

  for (let m = 144; ; m++) {
    let res = 2 * m * m - m;
    if (isPentagonal(res)) {
      return res;
  return null;

« Back to problem overview

All images are copyright to Project Euler