Euler Problem 4: Finding Palindrome numbers
The fourth Euler problem asks you to find the largest palindrome number that is the product of two three digit numbers. For example, the number 919 is a palindrome: it's the same forward and backwards.
To solve this problem, we need to find the product of all combinations of three digit numbers. Well, if you remember your probability, this is a combinatorial problem. Order doesn't matter. That limits the number of combinations.
Next, we need to find palindromes. A little string conversion makes that simple. You can convert the number to a string, then see if the string is equal to its reverse. Strangely, there isn't a method in System.String that can reverse a string. But, there is a Reverse() extension method that's in scope.
Well, let's look at the code:
1 static
void Main(string[] args)
2 {
3 var allProducts = from x in
Enumerable.Range(100, 900)
4 from y in
Enumerable.Range(100, 900)
5 where x <= y
6 let product = x * y
7 orderby product descending
8 select
new { x, y, product };
9
10 var palindrome = (from n in allProducts
11 let chars = n.product.ToString()
12 let reverse = new
string(chars.Reverse().ToArray())
13 where chars == reverse
14 select n).First();
15 Console.WriteLine("{0}, {1} => {2}", palindrome.x, palindrome.y,
16 palindrome.product);
17
18 }
The first query is to generate all products of three digit numbers. Notice that the where clause removes permutations that are the same as two numbers. For example, 251*126 would have already been computed from 126*251. Next, notice the 'let' clause. That assigns a local variable in the query expression so that you don't have to compute the product more than once. While we're at it, we order the values by the products in descending order.
The next query finds the palindromes from all those products. As I said earlier, I do this by converting the product to a string, then comparing the string to its reverse. As with the earlier query, I use the let clause to cache some local results and avoid recomputing values.
You'll need to run the code yourself to see the answer.