简体   繁体   中英

Largest palindrome which is product of two n-digit numbers (Python)

This is my implementation, but it not efficient when given 6 digit number.

Input  : n = 2
Output : 9009 

9009 is the largest number which is product of two

2-digit numbers. 9009 = 91*99.

def isPali(x):
n = str(x)
for i in range(len(n)):
    if not n[i] == n[-i-1]:
        return False
return True

def isProduct(x,A):
counter = A
while counter > 1:
    if x // counter <= A and x % counter == 0:
        return True
    else:
        counter-=1
return False

def largestProduct(A):
for i in range(A*A,1,-1):
    if isPali(i) and isProduct(i,A):
        return i
return False

largestProduct(999999)

Let x and y be the two n-digit factors of the palindrome number.

You can iterate over them in a descending number.

Key is to stop as soon as possible, which mean, once a first solution has been found, you don't check any product below that solution.

def get_max_palindrome(n):
    res = 0
    for x in range(10 ** n - 1, 1, -1):
        for y in range(10 ** n - 1, 1, -1):
            p = x * y
            if res > p:
                break
            if str(p) == str(p)[::-1]:
                res = p
                break
        if (x - 1) ** 2 < res:
            break
    return res


print(get_max_palindrome(6))

Exec in 0.378s on my laptop.

Codewise, this is not too difficult:

    n = 999999
    max_pali =0
    t = ()
    for i in range(1,n+1):
        for j in range(i,n+1):
            m = i*j
            s = str(m)
            if s == s[::-1] and m > max_pali:
                max_pali = m
                t = (i,j)
    print(max_pali,t)

However, this is a brute force approach. For numbers with 6 digits, this will not terminate in a reasonable amount of time. Even if it will, I could ask you the same question for 7 or 42 digits. I suggest you look for some structure, or property, of those numbers whose multiple is a palindrome. Could such a pair be any pair of numbers? Is the case 91*99 = 9009 a mere coincidence, or is there a pattern?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM