Project Euler 4 Problem Statement
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.
We can quickly brute force a solution by searching both factors downwards from 999 as it is more likely to find a larger product from larger factors. We test each product as a palindrome and save it and continue until we exhaust all of our potential factors.
From the list of products we search for the maximum as our result.
Here’s my initial simple brute-force solution; about 0.3 seconds, but not fast enough for The HackerRank Version.
A simple brute force method print max(i*j for i in xrange(100,1000) for j in xrange(i,1000) if str(i*j)==str(i*j)[::-1])
A post here demonstrates how to speed things up significantly. It summarizes that if a six digit number is palindromic it must follow the form:
Where a, b, and c are integers such that 1 ≤ a ≤ 9, b ≤ 9, c ≤ 9
So, for our product to be a palindrome one of our factors has to be a multiple of 11. This allows us to decrease our search index,
j, by 11 when
i is divisible by 11. Otherwise, when
i is not divisible by 11 we have to decrease
j by 1.
The final solution is presented below and performs an exhaustive investigation of 3-digit factors starting from the biggest factors until a maximum palindrome product is found1. There’s an early out condition that breaks the inside loop (
j) by finding a palindrome less than the current maximum. This is allowed because palindrome products are found in descending order from the perspective of the inside loop.
One subtle optimization was to check the limit before checking if the product is a palindrome as the palindrome check is more computationally expensive. If the first condition is false the succeeding conditions are ignored.
if p < L and is_palindromic(p): x, y, pmax = i, j, p
HackerRank specifies a limit, 101101 < N < 1000000. No changes are required.
Python 2.7 Source
The largest palindrome for some other cases (Note: I restricted the search range to something sane):
|# Digits||factor 1||factor 2||product|