Python Implementation of Problem 45
View source code here on GitHub!
Includes
math.hexagonal()
math.pentagonal()
math.triangle()
Problem Solution
Project Euler Problem 45
Problem:
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.
1"""
2Project Euler Problem 45
3
4Problem:
5
6Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
7Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
8Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
9Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
10
11It can be verified that T285 = P165 = H143 = 40755.
12
13Find the next triangle number that is also pentagonal and hexagonal.
14"""
15from .lib.math import hexagonal, pentagonal, triangle
16
17
18def main() -> int:
19 T_idx = 286
20 P_idx = 166
21 H_idx = 144
22 T_val = triangle(T_idx)
23 P_val = pentagonal(P_idx)
24 H_val = hexagonal(H_idx)
25 while not (T_val == P_val == H_val):
26 # print(P_val, T_val, H_val)
27 while T_val < P_val or T_val < H_val:
28 T_idx += 1
29 T_val = triangle(T_idx)
30 while P_val < T_val or P_val < H_val:
31 P_idx += 1
32 P_val = pentagonal(P_idx)
33 while H_val < P_val or H_val < T_val:
34 H_idx += 1
35 H_val = hexagonal(H_idx)
36 return T_val