Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Project Euler Problem #4

, 10 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
CodeProjectMoving on along with these Project Euler problems, Problem 4 states this:A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.Find the largest palindrome made from the product of two 3-digit numbers.This just

Moving on along with these Project Euler problems, Problem 4 states this:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
<br />
<br />Find the largest palindrome made from the product of two 3-digit numbers.

This just reeks of a brute force method. But that is fine. I don't think it will be that strenuous.

First we need a function that determines if a computed number is a palindrome. This is what I came up with:

 public bool IsPalindromic(string item)
 {
     return item.SequenceEqual(item.Reverse());
 }

Here we will take in a string representation of a number (or anything really) and use the handy 'SequenceEqual' and 'Reverse' extension methods. Now I actually read somewhere that the 'Reverse' method bogs down performance more than using any other method, but it wasn't enough to affect my performance so I kept it just because it is short and concise.

Now we have to iterate through all the possibilities and check if the given product is a palindrome. There are two ways I can do this:

Lambda:

 return Enumerable.Range(100, 900)
     .Select(i => Enumerable.Range(i, 1000 - i)
         .Where(j => newTools.IsPalindromic((i * j).ToString()))
         .Select(j => i * j)
         .OrderBy(j => j)
         .LastOrDefault())
     .Max();

Or Linq:

 return (from i in Enumerable.Range(100, 900)
         from j in Enumerable.Range(i, 1000 - i)
         let product = i * j
         where newTools.IsPalindromic(product.ToString())
         select product).Max();

Upon first glance the Linq option seems a lot cleaner and easier to read. And it might be. I guess I have no preference because both run just about as fast and return the correct answer, so it just depends on preference.

There ya go. Easy as pie.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jared Wallace
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 10 Aug 2011
Article Copyright 2011 by Jared Wallace
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid