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:

- Test to see if a number is a palindrome
- 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.

### Like this:

Like Loading...

*Related*

[…] 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 |

[…] 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 |