Monday, December 29, 2008

Project Euler and PowerShell - Problem 4

Problem 4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91X99. Find the largest palindrome made from the product of two 3-digit numbers.

function Reverse-Integer
for ($i = $str.ToString().Length - 1; $i -ge 0; $i--)
$c = $c + ($str.ToString().Substring($i,1))

$big = 0
for($x=100;$x -le 999;$x++)
for($y=100;$y -le 999;$y++)
$xy = $x*$y
$yx = Reverse-Integer $xy
if ($yx -eq $xy)
if ($xy -gt $big) {$big=$xy}

This one takes a long time to run. If anyone has any ideas on how to refactor this, please share!

1 comment:

Anonymous said...

Hi Wes,

Thanks a lot for your great blog posts. I know this one is quite old but anyway here is my approach:

function Get-ProdPalindrome{
#brute force all possible products into array
for($factor1=999;$factor1 -ge 10;$factor1--){
for($factor2=999;$factor2 -ge 100;$factor2--){
#sort array in descending order
#check for each product whether it is a Palindrome break after first hit
foreach ($currProd in $arrProds){
$arrProduct = [char[]] $currProd.ToString()
$reverse = [string]::join("",$arrProduct)

if ($currProd -eq [int]$reverse)
return $currProd