Duncan's blog

October 14, 2014

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

Filed under: PHP,Project Euler — duncan @ 8:00 am
Pentagram Vs. Hexagram

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;
$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.

1 Comment »

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

Blog at WordPress.com.

%d bloggers like this: