Duncan's blog

October 22, 2008

Project Euler: problem 4

Filed under: Coldfusion,Project Euler — duncan @ 7:00 am
Tags: , , , , ,

Problem 4:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.

Find the largest palindrome made from the product of two 3-digit numbers.

A nice simple one this time, at least if you’re using ColdFusion. Basically there are two steps to this:

  1. Test to see if a number is a palindrome
  2. Loop through the numbers
function isPalindrome(x)
	if (x EQ Reverse(x))
		return true;
		return false;

<cfset palindrome = 0>

<cfloop index="i" from="100" to="999">
	<cfloop index="j" from="100" to="999">
		<cfset x = i * j>
		<cfif x GT palindrome AND IsPalindrome(x)>
			<cfset palindrome = x>


Initially I split the number into two halves, reversed one half and compared it. Then I realised I could have just reversed the number itself to get the same result.

Then a pair of nested loops for doing the multiplication. There’s a bit of duplication, e.g. when i=900 and j=950, will give us the same result as when i=950 and j=900. However I’m guessing it’s not worth the effort to try and factor out those.

The only other thing worth mentioning is the order of the clauses in my if statement. Coldfusion uses lazy evaluation, meaning in a statement like IF A OR B, it will first evaluate A, and then only if A is false will it evaluate B. So I guessed that using the GT comparison is a quicker operation than running through my IsPalindrome function. So by moving that function call to the second clause, we only need to run it on those numbers that are bigger than what we already have.



  1. […] I reused the IsPalindrome function I wrote for Problem 4. The only new part here is working out a number in base 2. Coldfusion conveniently has a […]

    Pingback by Project Euler: problem 36 « Duncan’s blog — November 8, 2008 @ 11:25 am | Reply

  2. […] previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and […]

    Pingback by Project Euler: problem 4 (PHP) | Duncan's blog — September 22, 2014 @ 8:13 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 )

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

Create a free website or blog at WordPress.com.

%d bloggers like this: