pythonfor-loopif-statementpalindromehalting-problem

Python - long halt while calculating palindrome number


I'm trying to find largest palindromic number made from the product of two 3-digit numbers with my code. it works fine for 2-digit and 3-digit, but when I try it with 4-digit numbers, it doesn't work anymore. There is no output or "Process finished with exit code 0" at the end. It just halted like it was in an infinite loop.

palin = 0
for x in range(1, 10000):
    for y in range(1, 10000):
        mult = x * y

        if str(mult) == str(mult)[::-1]:
            if mult > palin:
                palin = mult

print(palin)

where did I go wrong? I just started Python about a month ago, so my code is still not effective


Solution

  • Your algorithm is not correct. The second if should be at the same level as mult = x*y.

    I modified your code a little bit. With the code below you see that the algorithm does not halt. It's just super slow. You'll have to wait for minutes.

    pa = 0
    for x in range(1, 10000):
        if x % 100 == 0:
            print(x)
        for y in range(x, 10000):
            m = x*y
            if str(m) == str(m)[::-1]:
                if m > pa:
                    pa = m
    print(pa)
    

    I changed the second range(1, 10000) to range(x, 10000) to eliminate duplicates like 1*2 and 2*1 into a single 1*2.

    If you want a speedup, consider switching to C or C++.

    Also you can reverse the iteration order for an extreme speedup

    for x in range(10000, 0, -1):
        for y in range(10000, 0, -1):
            m = x*y
            if str(m) == str(m)[::-1]:
                print(m)
                exit(0)