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. { 
  3.     if($text.Length -eq 1) 
  4.     { 
  5.         return $text 
  6.     } 
  7.     else 
  8.     { 
  9.         return (Reverse-Text($text.Substring(1, $text.Length-1))) + $text[0] 
  10.     } 
  11. } 
  12.  
  13. $start = 999 
  14. $end = 100 
  15. $max_palindrome = 0 
  16. for($num1 = $start; $num1 -ge $end; $num1--) 
  17. { 
  18.     for($num2 = $num1; $num2 -ge $end; $num2--) 
  19.     { 
  20.         $product = $num1*$num2 
  21.         if($product.ToString() -eq (Reverse-Text($product))) 
  22.         { 
  23.             if($product -gt $max_palindrome) 
  24.             { 
  25.                 $max_palindrome = $product 
  26.             } 
  27.         } 
  28.     } 
  29. } 
  30.  
  31. 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: