# 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
```<cfscript>
function isPalindrome(x)
{
if (x EQ Reverse(x))
return true;
else
return false;
}
</cfscript>

<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>
</cfif>
</cfloop>
</cfloop>

<cfoutput>#palindrome#</cfoutput>
```

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.