Click here to Skip to main content
15,896,730 members
Articles / All Topics

Project Euler Problem #4

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
10 Aug 2011CPOL 12.2K  
Project Euler Problem #4

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.

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:

C#
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:

C#
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:

C#
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)


Written By
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

Comments and Discussions

 
-- There are no messages in this forum --