Duncan's blog

October 11, 2014

Project Euler: problem 36 (PHP) – Double-base palindromes

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

36I 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 36:

The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)


$sum = 0;

function isPalindrome($x)
	return $x == strrev($x);

for ($i = 1;$i <= 999999; $i++) {
	if (isPalindrome($i) && isPalindrome(decbin($i))) {
		echo $i . " " . decbin($i) . "<br>";
		$sum += $i;

echo $sum;

Here I’m using the strrev() function to check if a string equals its reverse.

Then within my loop I’m using the decbin() function to convert my decimal numbers to their binary representation.

Make sure and read my mate Adam Cameron’s post on a completely different approach which is much cleverer and significantly faster.


Leave a Comment »

No comments yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Blog at WordPress.com.

%d bloggers like this: