Given
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.
Solution
import time
def reverse(num):
dreverse = 0
while (num > 0):
dreverse = dreverse * 10 + num % 10
num /= 10
return dreverse
def is_palindrome(num):
if (num < 0):
raise ValueError('Non-negative integers only')
return num == reverse(num)
def main():
largest_palindrome = 0
lower = 999
while lower >= 100:
upper = 999
while upper >= lower:
if upper * lower <= largest_palindrome:
break
if is_palindrome(upper * lower):
largest_palindrome = upper * lower
upper -= 1
lower -= 1
return largest_palindrome
start_time = time.time()
print main()
print("--- %s seconds ---" % (time.time() - start_time))
o/p: 906609
--- 0.0150721073151 seconds ---
I am including timing metric from now on. This solution seems \$O(N^2)\$. Can I improve it further?