I want to find the largest palindrome that can be obtained through the multiplication of two 3-digit numbers.
I started off with a and b both being 999, and to decre
You algorithm is wrong. You will need to test all values of a to all values of b, which can be solved by using two loops (the outer for a and the inner for b). I also suggest that you use a and b as loop indices, which simplifies the logic (makes it easier to keep in head).
Consider moving the palindrome check to it's own function as well, to make the code easier to understand.
I'm no Python programmer, but here's my solution in PHP:
function palindrome($x) {
$x = (string) $x; //Cast $x to string
$len = strlen($x); //Length of $x
//Different splitting depending on even or odd length
if($len % 2 == 0) {
list($pre, $suf) = str_split($x, $len/2);
}else{
$pre = substr($x, 0, $len/2);
$suf = substr($x, $len/2+1);
}
return $pre == strrev($suf);
}
$max = array(0, 0, 0);
//Loop $a from 999 to 100, inclusive.
//Do the same over $b for EVERY $a
for($a = 999; $a >= 100; $a--) {
for($b = 999; $b >= 100; $b--) {
$x = $a*$b;
if(palindrome($x)) {
echo $a, '*', $b, ' = ', $x, "\n";
if($x > $max[2]) {
$max = array($a, $b, $x);
}
}
}
}
echo "\nLargest result: ", $max[0], '*', $max[1], ' = ', $max[2];