Project Euler Problem 4 (PHP)

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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.

Script

Execution Time: 1.3709 seconds

$start = 999;
$r = array();

for ($x = $start; $x >= 100; $x--) {
    for ($y=$start; $y >= 100; $y--) {
        $p = $x*$y;
        if ($p == strrev($p)) {
            $r[] = $p;
        }
    }
}

rsort($r, SORT_NUMERIC);

echo $r[0].PHP_EOL;

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
This entry was posted in PHP, Programming, Project Euler and tagged , , , . Bookmark the permalink.

2 Responses to Project Euler Problem 4 (PHP)

  1. Kah Thong says:

    Hi thanks for your solution, however it tends to slow down on very large numbers (4 digits above)

    Here’s my not-so-clean solution, but I THINK it works.


    $start = microtime(TRUE);

    $palindrome = $palindrome_i = $palindome_j = 0;
    for ($i = 999; $i > 99; $i--) {
    for ($j = 999; $j > 99; $j--) {
    $product = $i * $j;
    if ($product == strrev($product)) {
    $palindrome_j = $j;
    $palindrome = $product;
    break;
    }
    }
    if ($palindrome) {
    $palindrome_i = $i;
    break;
    }
    }
    $palindrome2 = 0;
    for ($i = $palindrome_i; $i > $palindrome_j; $i--) {
    for ($j = $palindrome_i; $j > $palindrome_j; $j--) {
    $product = $i * $j;
    if ($product == strrev($product)) {
    $palindrome2 = $product;
    break;
    }
    }
    if ($palindrome2) {
    break;
    }
    }
    echo ($palindrome2) ? $palindrome2 : $palindrome;

    $end = microtime(TRUE);
    echo '' . number_format($end - $start, 4) . ' seconds';

    Just sharing here, I could be wrong.

    • Joseph says:

      I haven’t had a chance to run through the code just yet, but it runs beautifully as well as much more efficiently than mine. Thank you!