Project Euler Problem 045

Statement

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

In this case we know that the hexagonal is the function that grows faster so we increase
that. Then we increase the others until they equal or pass the obtained value. If the 3 values
aren't equal, we repeat the process.

if __name__ == '__main__':
    iT = 286
    iP = 166
    iH = 144
 
    t = iT * (iT + 1) // 2
    p = iP * (3 * iP - 1) // 2
    h = iH * (2 * iH - 1)
 
    while h != t or t != p:
        h = iH * (2 * iH - 1)
        iH += 1
        while t < h:
            t = iT * (iT + 1) // 2
            iT += 1
        while p < h:
            p = iP * (3 * iP - 1) // 2
            iP += 1
    print("The result is:", h)

The Python file is available for download here.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License