Largest palindrome product

Problem 4

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.

Ans:- 906609

Program:

def compute():
	ans = max(i * j
		for i in range(100, 1000)
		for j in range(100, 1000)
		if str(i * j) == str(i * j)[ : : -1])
	return str(ans)

print(compute())

Programming Problem of this from Hackerrank.com

 

A palindromic number reads the same both ways. The smallest 6 digit palindrome made from the product of two 3-digit numbers is 101101= 143 x 707.

Find the largest palindrome made from the product of two 3-digit numbers which is less than N .

Input Format

First line contains T  that denotes the number of test cases. This is followed by T  lines, each containing an integer, N .

Constraints

  • 1⩽T⩽100
  • 101101<N<1000000

Output Format

Print the required answer for each test case in a new line.

Sample Input 

2
101110
800000

Sample Output 

101101
793397

 

Explanation 

  • 101101 is product  of 143 and 707 .
  •  793397 is product of  869 and 913.

Solution:-

 

1) Simply find all the palindrome number that are the product of two 3-digits numbers, because they are limited and easy to find.

2) Store them in a list and sort it

3) Go through the list and find which number is smaller than n and break the loop, print the number we find

import sys
palindromelist = []
for i in range(100, 1000):
    for j in range(100, 1000):
        a = i * j
        if str(a) == str(a)[::-1] and a not in palindromelist:
            palindromelist.append(a)
palindromelist.sort()
length = len(palindromelist)


n = int(input())
for _ in range(n):
    a = int(input())
    for i in range(length - 1, -1, -1):
        if palindromelist[i] < a:
            print(palindromelist[i])
            break