Thursday, September 10, 2009

Euler 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 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Powershell Solution:

  1. function Reverse-Text([string] $text
  2.     if($text.Length -eq 1) 
  3.     { 
  4.         return $text 
  5.     } 
  6.     else 
  7.     { 
  8.         return (Reverse-Text($text.Substring(1, $text.Length-1))) + $text[0] 
  9.     } 
  10.  
  11. $start = 999 
  12. $end = 100 
  13. $max_palindrome = 0 
  14. for($num1 = $start; $num1 -ge $end; $num1--) 
  15.     for($num2 = $num1; $num2 -ge $end; $num2--) 
  16.     { 
  17.         $product = $num1*$num2 
  18.         if($product.ToString() -eq (Reverse-Text($product))) 
  19.         { 
  20.             if($product -gt $max_palindrome
  21.             { 
  22.                 $max_palindrome = $product 
  23.             } 
  24.         } 
  25.     } 
  26.  
  27. echo $max_palindrome 
Note: The solution may not be the optimized one… just a quick hack… I’ll revisit later for optimization if time permits… :-)

No comments: