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:

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.

## No comments:

## Post a Comment