Back to Project Euler

Previous Problem Next Problem

Problem 4: Largest Palindrome Product

A palindromic number reads the same both ways. The largest palindrome made from the product of two \(2\)-digit numbers is \(9009 = 91 \times 99\).

Find the largest palindrome made from the product of two \(3\)-digit numbers.

Solution

To check whether a number is a palindrome, we can convert it into a string, and then see if reversing the string leaves it unchanged. There are other ways, but this is probably the simplest to implement.

Brute-force search appears to be the way to go, but we can still optimize it a little. Let the outer loop be over the larger of the two numbers, which we'll call \(a\), from 999 downward, and let the inner loop be over the number \(b\), going from \(a\) downward. If \(ab\) isn't greater than the largest palindrome we've found, we know we can't improve our answer for the current choice of \(a\), so we break out of the inner loop. If \(a^2\) isn't greater than the largest palindrome, we know that we can't improve our answer for any subsequent choice of \(a\), so we return.

Python Code

def p4():
	res = 0
	for a in range(999, 0, -1):
		if a ** 2 <= res:
			return res
		for b in range(a, 0, -1):
			if a * b <= res:
				break
			s = str(a * b)
			if s == s[::-1]:
				res = a * b

Previous Problem Next Problem

Back to Project Euler