# Duncan's blog

## October 14, 2014

### Project Euler: problem 45 (PHP) – Triangular, pentagonal, and hexagonal

Filed under: PHP,Project Euler — duncan @ 8:00 am

Picture courtesy of Ze’ev Barkan

I 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 I’d appreciate any feedback on my PHP code.

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.

Code:

```<?php
function isTriangle(\$x) {
\$number = (sqrt((8 * \$x) + 1) - 1) / 2;

return isInteger(\$number);
}

function isPentagonal(\$x) {
\$number = (sqrt((24 * \$x) + 1) + 1) / 6;

return isNaturalNumber(\$number);
}

function isHexagonal(\$x) {
\$number = (sqrt((8 * \$x) + 1) + 1) / 4;

return isInteger(\$number);
}

function isInteger(\$number) {
return \$number == round(\$number);
}

function isNaturalNumber(\$number) {
return isInteger(\$number) && \$number > 0;
}

\$number = 1;

while (true) {
if (\$number > 40755 && isTriangle(\$number) && isPentagonal(\$number) && isHexagonal(\$number)) {
break;
}
}

echo \$number;
```

Nothing too fancy, basically the same as I had previously with CFML.  On the previous problem I used intval() to check if a number was an integer.  Here I’m using round() to do the same thing.  I tried using is_int(), however that just seemed to time out.