Problem description:
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.
Palindrome:
In math, a palindrome is a number that reads the same forward and backward.
Example:
353, 787, and 2332 are examples of palindromes.
By definition, all numbers that have the same digits such as 4, 11, 55, 222, and 6666 are examples of palindromes.
Step-by-Step my code:
1- largest number of n-1 digit. For example, for n = 2, upper_limit is 99
2- One plus this number is lower limit which is product of two numbers. For example, for n = 2, lower_limit is 10.
3- calculating product of two n-digit numbers
4- calculating reverse of product to check whether it is palindrome or not
5- update new product if exist and if greater than previous one
My Solution
This is my solution for problem 4 of Project Euler using Python:
def largest_palindrome_product(n):
'''Find Largest Palindrome Product
'''
upper_limit = (10**(n))-1
lower_limit = 1 + upper_limit//10
max_product = 0
for i in range(upper_limit,lower_limit-1, -1):
for j in range(i,lower_limit-1,-1):
product = i * j
if (product < max_product):
break
number = product
reverse = 0
while (number != 0):
reverse = reverse * 10 + number % 10
number =number // 10
if (product == reverse and product > max_product):
max_product = product
return max_product
n
supposed to be 6, since 10**6-1 is a good upper bound on products of two 3-digit numbers? \$\endgroup\$n=3
, since this sets the bounds for the multiplied values at999
and100
. \$\endgroup\$