# Project Euler 45: 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.

## Solution

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 (var res = 0, m = 144; ; m++) { res = 2 * m * m - m; if (isPentagonal(res)) { return res; } } return null; }