After completing problem 42, which required checking if a number was a triangular number, this problem was a natural progression. This time we’re also wanting to check if our number is a hexagonal number and pentagonal number.

Problem 45:

*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(3n1)/2 1, 5, 12, 22, 35, …

Hexagonal H_{n}=n(2n1) 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.*

So again, thanks to Wikipedia for the formulae, I just added a couple functions to test if any number is hexagonal and pentagonal.

<cfscript>
function isTriangle(x)
{
var n = (SQR((8 * x) + 1) - 1) / 2;
if (n EQ Round(n))
// it's an integer
return true;
else
// it's not an integer, therefore not a triangle number
return false;
}
function isPentagonal(x)
{
var n = (SQR((24 * x) + 1) + 1) / 6;
if (n EQ Round(n) AND n GT 0)
// it's a natural number
return true;
else
// it's not a natural number, therefore not a pentagonal number
return false;
}
function isHexagonal(x)
{
var n = (SQR((8 * x) + 1) + 1) / 4;
if (n EQ Round(n))
// it's an integer
return true;
else
// it's not an integer, therefore not a triangle number
return false;
}
</cfscript>
<cfset i = 1>
<cfset add = 2>
<cfloop condition="1 GT 0">
<cfset i = i + add>
<cfset add = add + 1>
<cfif IsTriangle(i) AND isPentagonal(i) AND isHexagonal(i) AND i GT 40755>
<cfbreak>
</cfif>
</cfloop>
<cfoutput>#i#</cfoutput>

Initially I started out at i=40755, and incremented one at a time. However that seemed to be rather slow. So instead I decided to start at 1, so I could keep track of how much to increment each time; using the series of triangle numbers rather than either of the others, just because that was simplest.

### Like this:

Like Loading...

*Related*

[…] is given to us. I already had a formula for the reverse, checking if a number is pentagonal, from problem 45. To calculate the square root, I needed to import the math […]

Pingback by Project Euler problem 44 « Duncan’s blog — December 12, 2009 @ 3:09 pm |

[…] previously blogged about this Project Euler puzzle nearly 6 years ago, using ColdFusion. This is my approach using PHP as a simple practical exercise for myself, and […]

Pingback by Project Euler: problem 45 (PHP) – Triangular, pentagonal, and hexagonal | Duncan's blog — October 14, 2014 @ 8:07 am |