Project Euler: Problem 4

Problem: Find the longest palindrome made from the product of two three-digit numbers.

Q: How do we work out if a number is a palindrome?
A: Convert it to a string and compare it with the reverse of the string. PHP has a built-in function, strrev, which makes this trivial.

Solution: Given the search space involved, we can simply test all the products of two three-digit numbers using a nested loop.

<?php

declare(strict_types=1);
error_reporting(E_ALL);

function is_palindrome(int $number) : bool
{
    // A number is a palindrome if its string representation
    // is the same when reversed
    $str = strval($number);
    return ($str === strrev($str));
}

$longest_palindrome = 0;

for ($i = 100; $i <= 999; $i++)
{
    for ($j = 100; $j <= 999; $j++)
    {
        $product = $i * $j;

        if (is_palindrome($product) && $product > $longest_palindrome)
        {
            $longest_palindrome = $product;
        }
    }
}

print("$longest_palindrome\n");

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.