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 loops 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, and not the largest product of two numbers up to three digits that was palindrome.
To do with two numbers, use i * j
, where I use a loop inside the other, one traversing the values of i
and other the values of j
. The value of j
is initialized with j = i
instead of j = 0
because once multiplication is commutative, the values of j
who are less than i
are repeated and therefore unnecessary to be tested.
Another problem you had is that when you found a palindrome, you already assigned 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 found palindrome, not the largest palindrome. The solution to this was to use a variable polTemp
and only attribute it to pol
if polTemp > pol
.
See here working on ideone.
It worked fine thanks!
– Bruno Santos
Now that you commented I realized the bullshit I was doing searching only in the multiples of 999.
– Bruno Santos
The accountants
i
andj
may start at 100, since only the product of 3-digit numbers is to be considered.– Woss
@Brunosantos If this answer solved your problem and there was no doubt left, I ask you to mark it as accepted/correct by clicking below the vote number.
– Victor Stafusa
@Andersoncarloswoss This is debatable, since 012 may or may not be considered a three-digit number.
– Victor Stafusa
I disagree. Mathematically speaking even the value 012 has two digits. We are working with numbers, not strings.
– Woss
@Andersoncarloswoss That’s why I said it’s debatable, it can be argued both against and for and depends on the desired context. However, this program works independently of what interpretation is given for "three-digit number".
– Victor Stafusa