Created With

# linkProblem 45 - Triangular, pentagonal, and hexagonal

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.

euler_045.py1linkimport itertools2link3linkdef is_triangular(n):4link    if (((8*n) + 1) ** 0.5) % 1 == 0:5link        return True6link    else:7link        return False8link9link10linkdef is_pentagonal(n):11link    if (((((24 * n) + 1) ** 0.5) + 1) / 6) % 1 == 0 :12link        return True13link    else:14link        return False15link16link17linkdef is_hexagonal(n):18link    if (((((8 * n) + 1) ** 0.5) + 1) / 4) % 1 == 0 :19link        return True20link    else:21link        return 22link23link24linkdef generate_triangle_number(n):25link    return (n+1) * n * 0.526link27link28linkskip = [1, 40755]29linkfor i in itertools.count():30link    triangle = generate_triangle_number(i)31link    if triangle not in skip and is_pentagonal(triangle) and is_hexagonal(triangle):32link        print(triangle)33link        break

• We first create functions that tests if a number is triangular, pentagonal, and hexagonal. Similar to Euler problem 42, these formula can be derived.
• This function will generate the nth triangle number.
Sample usage:chevron_right
1linkn = 12linkprint(generate_triangle_number(n))3link14link5linkn = 56linkprint(generate_triangle_number(n))7link15
• We will skip 1 and 40755 (because we want to find the NEXT triangle number that is also pentagonal and hexagonal)
• This will create an iterator that contains consecutive numbers starting from zero.
• Then we generate a triangle number from that.
• If the generated triangle number is not 1 nor 40755, and is also pentagonal, and hexagonal, the loop breaks. That is our answer.