I previously blogged about this Project Euler puzzle over 5 years ago, using Python. This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 44:

*Pentagonal numbers are generated by the formula, P*_{n}=n(3n−1)/2. The first ten pentagonal numbers are:

*1, 5, 12, 22, 35, 51, 70, 92, 117, 145, …*

*It can be seen that P*_{4} + P_{7} = 22 + 70 = 92 = P_{8}. However, their difference, 70 − 22 = 48, is not pentagonal.

*Find the pair of pentagonal numbers, P*_{j} and P_{k}, for which their sum and difference is pentagonal and D = |P_{k} − P_{j}| is minimised; what is the value of D?

Code:

<?php
function getPentagonal($x) {
return $x * (3 * $x - 1) / 2;
}
function isPentagonal($x) {
$n = (sqrt((24 * $x) + 1) + 1) / 6;
return $n == intval($n) && $n > 0;
}
$i = 0;
$pentagonals = [];
while (true) {
$i++;
$p = getPentagonal($i);
foreach ($pentagonals as $j) {
$diff = abs($p - $j);
if (isPentagonal($diff)) {
$intSum = $p + $j;
if (isPentagonal($intSum)) {
echo "solution:" . $diff;
break 2;
}
}
}
$pentagonals[] = $p;
}

A fraction simpler code than with Python. Similar to Problem 45, you’d assume PHP’s is_int() function would be useful at working out whether a value is an integer. However it just seems to time out here (numbers too large? can’t handle load?), so I’m comparing a number to its integer component via the intval() function instead.

### Like this:

Like Loading...

*Related*

[…] 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 […]

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

Rewrite for coding styles, add an isInteger function which uses is_int(), link to article for Pentagonal numbers formula.

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