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 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.*

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;
$add = 2;
while (true) {
$number += $add;
$add++;
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.

### Like this:

Like Loading...

*Related*

Rewrite this to have isNatural and isInteger functions, apply clean coding standards, try using is_int() instead of round() or intval(), link to articles for source of hexagonal etc formulas

Comment by duncan — October 14, 2014 @ 9:29 am |