#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. largestPalindrome = 0 pi = 0 pj = 0 exitAll = False #loop over numbers from 999 to 100 in reverse order for i in range(999,99,-1): #this will get set when we want to exit all #loops, when none of the remaining #products can possibly be more than the #largest palindrome. if exitAll: break #loop from 999 to i #so we don't have to double #check numbers because x * y == y * x for j in range(999,i-1,-1): product = i * j #if the product is less than the largestPalindrome #then we show just exit the loop, and move #onto the next item in the outer loop #if we have only checked the first value of J # (999), then we should just exit # altogether, because no other products # will be > largest palindrome if product < largestPalindrome: if j == 999: exitAll = True break #convert the product to a string sprod = "%d" % (product,) #check if the product is the same #forwards as backwards if sprod == sprod[::-1]: #if it's a palendrome #and larger the largest, #we set it to the largest largestPalindrome = product pi = i pj = j print "The largest palendrome is %d" % (largestPalindrome,) print "it is the product of %d and %d" % (pi,pj)