Find the largest palindrome made from the product of two 3-digit numbers - Python

1

I have a problem. I'm creating an algorithm in Python to find the largest palindrome made from the product of two 3-digit numbers.

Code:

i = 0
while i <= 999:
    temp = str(i * 999)
    tempInverso = temp[::-1]
    if temp == tempInverso:
        pol = int(temp)    
    i += 1
print(pol)

It returns me the value 90909 , but the correct value is 906609 . Since I do not think anything wrong with the code, I've come to get help from you. Thank you all for the attention.

    
asked by anonymous 02.08.2017 / 22:19

2 answers

3

This one works:

i = 0
j = 0
pol = 0
while i <= 999:
    j = i
    while j <= 999:
        temp = str(i * j)
        tempInverso = temp[::-1]
        if temp == tempInverso:
            polTemp = int(temp)
            if polTemp > pol:
                pol = polTemp
        j += 1
    i += 1
print(pol)

Note that there are two links here. The reason is because what you did, you had i * 999 , that is, you were looking for the largest multiple of 999 that was palindrome, not the largest product of two numbers up to three digits that was palyndrome.

To do with two numbers, use i * j , where I use a loop inside the other, one going through the values of i and another the values of j . The j value is initialized with j = i instead of j = 0 because since multiplication is commutative, j values that are less than i are repeated and therefore unnecessary to be tested.

Another problem that you had is that when you find a palindrome, you already assign it to the variable pol , without checking if this palindrome is better than the previous one already found. As a result, it would show the last palyndrome found, not the largest palyndrome. The solution to this was to use a polTemp variable and only assign it to pol and polTemp > pol .

See here working on ideone.

    
02.08.2017 / 22:35
2

Another possible solution:

from itertools import product

palindromes = (i*j for i, j in product(range(100, 1000), repeat=2) if str(i*j) == str(i*j)[::-1])

print("O maior palíndromo encontrado foi", max(palindromes))
  

See working at Ideone .

The product(range(100, 1000), repeat=2) function will generate all two-to-two combinations of values between 100 and 999. A loop of repetition is made on this list, storing the first value in i and the second in j . The i*j value is returned to the final list if the str(i*j) == str(i*j)[::-1] condition is true. With this, palindromes will be a generator with all palindromes product result between two three-digit values. With the max function we get the largest of them.

    
02.08.2017 / 23:04