The problem
What I like about Project Euler problems, even though in the end the coded solution is not that exciting, is that they expose me to topics I have never heard of before. In this particular case triangular, pentagonal and hexagonal numbers.
Also the result itself is astonishing. As given, 40755 is a number that is triangular, pentagonal and hexagonal. The next number that satisfies this condition, 1533776805, is really far away.
Triangular, pentagonal, hexagonal?
But first things first. What are triangular, pentagonal and hexagonal numbers? As Wikipedia and Wolfram MathWorld do a much better job than me at giving you all the details, I try to keep this section brief.
Triangular numbers
The function for creating triangular numbers is T(n) = n * (n + 1) / 2.
n = 1 → T(1) = 1;
n = 2 → T(2) = 3;
n = 3 → T(3) = 6;
n = 4 → T(4) = 10;
…
For each n you add up all the numbers from 0 to n, including n:
n = 1 → 0 + 1 = 1
n = 2 → 0 + 1 + 2 = 3
n = 3 → 0 + 1 + 2 + 3 = 6
n = 4 → 0 + 1 + 2 + 3 + 4 = 10
…
So what about the “triangular” part? Triangular numbers form equilateral triangles.
Three circles can be arranged to form an equilateral triangle of side length 2. An equilateral triangle of side length 3 requires 6 circles. And so on…
For more details see:
Pentagonal numbers
The function for creating pentagonal numbers is T(n) = n * (3 * n – 1) / 2.
n = 1 → T(1) = 1;
n = 2 → T(2) = 5;
n = 3 → T(3) = 12;
n = 4 → T(4) = 22;
…
Pentagonal numbers form nested equilateral pentagons.
Again, for more details see:
Hexagonal numbers
The function T(n) = n * (2 * n – 1) creates hexagonal numbers.
n = 1 → T(1) = 1;
n = 2 → T(2) = 6;
n = 3 → T(3) = 15;
n = 4 → T(4) = 28;
…
Pentagonal numbers form nested equilateral pentagons, guess what, hexagonal numbers form nested hexagons.
And again:
Comparison and similarities
The following diagram shows how the numbers grow in comparison.
It looks like I will at least need the data type long in my code.
Also according to Wolfram Mathworld all three numbers are related to each other:
-
Every pentagonal number is 1/3 of a triangular number.
-
Every hexagonal number is a triangular number[…].
Code
As every hexagonal number also is a triangular number, triangular numbers can be ignored.
All I have to do is…
- …to start with 144 (see problem description above)…
- …create hexagonal numbers for 144, 145, 146 and so on…
- …and check if the created hexagonal number is a pentagonal number as well.