Search code examples
pythonpalindrome

Palindrome from the product of two 3-digit numbers


I want to find the largest palindrome that can be obtained through the multiplication of two 3-digit numbers.

I started off with a and b both being 999, and to decrement a and b with every multiplication that occurred.

a = 999 #Defining Variables
b = 999

for i in range (1000): 
    c= a*b                          #multiply a to b
    if int(str(c)[::-1]) == c:
        print c
    a = a-1                         #decrement the value of a
    c=a*b                           #multiply a by the decremented a
    if int(str(c)[::-1]) == c:
        print c

    b = b-1                         #decrement b so that both a and b have been decremented

The result has turned up 698896, 289982, 94249, 69696... with 698896 being the first number. Currently I'm still trying to figure out what I'm missing.


Solution

  • You cannot decrement a and b in an alternating fashion, because you're missing value pairs like a = 999 and b = 997 that way.

    Try nested looping instead, starting from 999 and counting backwards.

    Something like

    def is_pal(c):
        return int(str(c)[::-1]) == c
    
    maxpal = 0
    for a in range(999, 99, -1):
        for b in range(a, 99, -1):
            prod = a * b
            if is_pal(prod) and prod > maxpal:
                maxpal = prod
    
    print maxpal
    

    EDIT: Modified lower bounds after Paul's comment.