Triangular, Pentagonal, and Hexagonal
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle: T_n = n(n+1)/2, sequence: 1, 3, 6, 10, 15, ...
Pentagonal: P_n = n(3n-1)/2, sequence: 1, 5, 12, 22, 35, ...
Hexagonal: H_n = n(2n-1), sequence: 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.
Implementations
// https://projecteuler.net/problem=45
// 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.
// Answer: 1533776805
// Authored by: Tim Varley š
#include <iostream>#include <cmath>
long long triangular_pentagonal_hexagonal() { for (long long n = 144; ; n++) { long long h = n * (2 * n - 1); double k = (1 + sqrt(1 + 24.0 * h)) / 6; if (k == floor(k)) { return h; } } return 0;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << triangular_pentagonal_hexagonal() << std::endl;}#endif // UNITTEST_MODESolution Notes
Mathematical Background
These sequences share common terms. The problem notes that , and asks for the next such number.
Algorithm Analysis
Since every hexagonal number is also a triangle number (because ), the problem reduces to finding hexagonal numbers that are also pentagonal.
The solution iterates through hexagonal numbers starting from n=144 (since H_{143}=40755), and checks if each is pentagonal using the inverse formula.
For a number x to be pentagonal, solve for integer n. This gives .
Performance Analysis
- Time Complexity: O(k) where k is the number of hexagonal numbers checked until a match is found
- Space Complexity: O(1)
- Execution Time: Very fast (<1ms), finds the answer quickly
- Scalability: Linear in the distance between solutions
Key Insights
-
Hexagonal numbers are a subset of triangular numbers
-
The next common number after 40755 is 1533776805 (H_{27693} = T_{55385} = P_{31977})
-
Using floating-point square root for integer checking requires careful precision handling
-
The sequence of such numbers grows rapidly
Educational Value
This problem teaches:
-
Figurate number relationships and set theory
-
Inverse formula derivation for number sequences
-
Precision issues in floating-point computations
-
Efficient checking algorithms for mathematical properties
-
The connection between different polygonal number sequences