according to the problem:
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.
Here is my code:
def largest_palindrome_product(n:int) -> int: ''' Returns largest palindrome whose a product of two n digit(base 10) integer :param n: the number of digits in the numbers we compute the product of :return: largest palindrome whose a product of two n digit(base 10) integer or -1 if non were found ''' # Dealing with edge cases if n == 1: return 9 elif n < 1: raise ValueError("Expecting n to be >= 1") mul_max = -1 upper_boundary = (10**n) - 1 lower_boundary = 10**(n-1) # Searching for the largest palindrome between the upper boundary and the lower one. for i in range(upper_boundary, lower_boundary, -1): for j in range(i, lower_boundary, -1): str_prod = str(i*j) if i*j > mul_max and str_prod[::-1] == str_prod: mul_max = i*j return mul_max
Here is a small test case for this code:
from ProjectEuler.problem4 import largest_palindrome_product if __name__ == "__main__": # largest prime product is of 91*99 -> returns 9009 print(largest_palindrome_product(2)) # Checking edge cases -> returns 9 print(largest_palindrome_product(1)) # largest prime product is of 993*913 -> returns 906609 print(largest_palindrome_product(3))
Let me know your thoughts on this solution :)