Another pretty easy one from
Project Euler, puzzle 4 simply required building an array of values based on calculations and sorting them to find the highest values:
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.
I basically had two variables looping from 999 to 100, multiplying them together for each value. I then converted the value to a string and reversed it, if the reversed string equals the original string the number is palindromic so I added it to an array (making sure to add the number and not the string or ordering the array would work alphabetically rather than numerically).
I then reversed the order of the array and output the first element:
<?
/******************************************************************
* ProjectEuler.net * Problem 4 * 2010-05-31 * Martin Caine *
******************************************************************/
//create an array to store the results
$numbers = array();
// loop from 999 to 100
for( $x=999; $x>99; $x-- )
{
// loop the second value from 999 to 100
for( $y=999; $y>99; $y-- )
{
$number = $x * $y;
// test if the number is palindromic
if( strval( $number ) == strrev( strval( $number ) ) )
{
// if it's not already in our array, add it now
if( !in_array( $number, $numbers ) )
{
$numbers[] = $number;
}
}
}
}
// sort the numbers in reverse order
rsort( $numbers );
// output the highest number
echo $numbers[0];
?>
If you found this post helpful please leave a comment below: