# Euler Problem 4¶

Back to overview.

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.

No big magic going on in this solution. We apply brute force. The only optimization we take is starting from the back so that the first palindrome should be the largest. However, we first implement a simple function to check whether an integer is a palindrome.

In [1]:

    def is_palindrome(n):
        assert(type(n) is int)
        n = str(n)
        a, b = 0, len(n) - 1
        while a < b:
            if n[a] != n[b]:
                return False
            a += 1
            b -= 1
        return True

    assert(is_palindrome(9009) is True)
    assert(is_palindrome(909) is True)
    assert(is_palindrome(1) is True)
    assert(is_palindrome(908) is False)

Get potential solutions. Generating a list comprehension which sorts the products in decreasing order is actually not that easys. This is because if we use two ranges it is not straight foward to decide which product is smaller or bigger. In the following example. 9 times 7 is still bigger than 8 times 8, but 9 times 6 is not anymore. So let's go for brute force the hard way.

In [2]:

    pairs = ((a, b) for a in range(9, 0, -1) for b in range(a, 0, -1))
    print(list(pairs))

    [(9, 9), (9, 8), (9, 7), (9, 6), (9, 5), (9, 4), (9, 3), (9, 2), (9, 1), (8, 8), (8, 7), (8, 6), (8, 5), (8, 4), (8, 3), (8, 2), (8, 1), (7, 7), (7, 6), (7, 5), (7, 4), (7, 3), (7, 2), (7, 1), (6, 6), (6, 5), (6, 4), (6, 3), (6, 2), (6, 1), (5, 5), (5, 4), (5, 3), (5, 2), (5, 1), (4, 4), (4, 3), (4, 2), (4, 1), (3, 3), (3, 2), (3, 1), (2, 2), (2, 1), (1, 1)]

We iterate over all 3-digit pairs. Two avoid duplicates the second range starts at the current value of the first range. If the new product is greater than the old one and a palindrome we have found a new result.

In [4]:

    import timeit

    def brute_force():
        r = 0
        for a in range(999, 99, -1):
            for b in range(a, 99, -1):
                c = a * b
                if c > r and is_palindrome(c):
                    r = c
        return r

    print(timeit.timeit(brute_force, number=100))
    print(brute_force())

    2.844880788875627
    906609

To do some more optimization we can simply break the loops if the square of the outer loop is smaller than the current result. If we find the solution quiet early this will prevent iterating through a lot of values which cannot yield a better result.

In [5]:

    def brute_force():
        r = 0
        for a in range(999, 99, -1):
            if a * a < r:
                break
            for b in range(a, 99, -1):
                c = a * b
                if c > r and is_palindrome(c):
                    r = c
        return r

    print(timeit.timeit(brute_force, number=100))
    print(brute_force())

    0.562125718678324
    906609