# Duncan’s blog

## November 4, 2008

### Project Euler: problem 45

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 Tn=n(n+1)/2 1, 3, 6, 10, 15, …
Pentagonal Pn=n(3n1)/2 1, 5, 12, 22, 35, …
Hexagonal Hn=n(2n1) 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.

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>

<cfloop condition="1 GT 0">
<cfset i = i + add>
<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.