Algorithm Training/5%

#4 Largest palindrome product

Hwigang Lee 2022. 1. 28. 11:31

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.


더보기

The problem requires the largest, so I'll go backward.

for i in range(999, 99, -1):
    p = int(str(i) + str(i)[::-1])

This gives all the palindromes from 999999 to 100001 (If I have to find the smallest one, I should have to consider the odd-digit palindromes).

What I have to do now is to find out if this is evenly divided by two 3-digit numbers.

for j in range(999, 99, -1):
    if p % j == 0 and int(p / j) < 1000:
        print(f"{p}={j}×{int(p / j)}")

If I find the first one, I don't need the rest.

indicator = True
for i in range(999, 99, -1):
    if indicator:
        p = int(str(i) + str(i)[::-1])
        for j in range(999, 99, -1):
            if p % j == 0 and int(p / j) < 1000:
                print(f"{p}={j}×{int(p / j)}")
                indicator = False
                break

That's it!

Put a last touch for the other digits. I made the variable 'digit' start from 2. All the 2-digit palindrome numbers are multiples of 11; thus cannot be made by multiplying two natural numbers under 10.

digit = 3
indicator = True
if digit < 2:
    print(False)
else:
    for i in range(10 ** digit - 1, 10 ** (digit - 1) - 1, -1):
        if indicator:
            p = int(str(i) + str(i)[::-1])
            for j in range(10 ** digit - 1, 10 ** (digit - 1) - 1, -1):
                if p % j == 0 and int(p / j) < 10 ** (digit):
                    print(f"{p}={j}×{int(p / j)}")
                    indicator = False
                    break

If the 'digit' is set to 2, then this code gives 9009=99×91, which is the same as in the example. And for 3, the answer is 906609.

'Algorithm Training > 5%' 카테고리의 다른 글

#8 Largest product in a series  (0) 2022.02.03
#6 Sum square difference  (0) 2022.02.01
#3 Largest prime factor  (0) 2022.02.01
#5 Smallest multiple  (0) 2022.01.30
#2 Even Fibonacci numbers  (0) 2022.01.24