简体   繁体   English

最大回文集,是两个n位数字的乘积(Python)

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

This is my implementation, but it not efficient when given 6 digit number. 这是我的实现,但是给定6位数字时效率不高。

Input  : n = 2
Output : 9009 

9009 is the largest number which is product of two 9009是最大的数,是两个的乘积

2-digit numbers. 2位数字。 9009 = 91*99. 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. 令x和y为回文数的两个n位因子。

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. 在笔记本电脑上以0.378秒执行。

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. 对于6位数字,这不会在合理的时间内终止。 Even if it will, I could ask you the same question for 7 or 42 digits. 即使可以,我也可以问您同样的7位或42位数字问题。 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? 91 * 99 = 9009只是一个巧合,还是有规律?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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