Project Euler Solution 45: Triangular, pentagonal, and hexagonal

Problem 45: Triangular, pentagonal, and hexagonal from the Project Euler series is actually pretty lame given the functionality that we have developed for the past problems.

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

Kind Formula Examples
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.

The problem statement asks for the next triangle number, but it makes more sense to look for the next hexagonal number. Since they have to be the same, it doesn't metter. And the heaxonal numbers step faster, so we have to check less numbers.

We use the check for triangular numbers from Solution 42: Coded triangle numbers and the check for pentagonal numbers from Solution 44: Pentagon numbers to just check these numbers. By going through the hexagonal numbers we don't even have to write a check for them.

def solution() -> int:
    for n in itertools.count(144):
        hex_n = n * (2 * n - 1)
        if is_pentagonal(hex_n) and is_triangle_number(hex_n):
            return hex_n

This runs in 14 ms, so it is quite fast enough.

All hexagonal numbers are also triangular numbers with the mapping $H_n = T_{2n-1}$. Therefore one could also let go of that check. Since we check for pentagonal numbers first, we already know that the one hexagonal number that is a pentalgonal number must also be a triangular number. Therefore this check is evaluated exactly once and doesn't cost us anything measureable.