Duncan's blog

October 13, 2014

Project Euler: problem 44 (PHP) – Pentagon numbers

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

HexI 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, 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.

2 Comments »

  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 | Reply

  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 | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: