# Duncan's blog

## October 13, 2014

### Project Euler: problem 44 (PHP) – Pentagon numbers

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

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.

Pentagonal numbers are generated by the formula, Pn=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 P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk − Pj| 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.

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

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

Create a free website or blog at WordPress.com.