Skip to main content
 首页 » 编程设计

python之两个三位数乘积的回文

2025年05月04日9jiqing9006

我想找到两个三位数相乘可以得到的最大回文数。

我从 a 和 b 都是 999 开始,并在每次乘法时递减 a 和 b。

a = 999 #Defining Variables 
b = 999 
 
for i in range (1000):  
    c= a*b                          #multiply a to b 
    if int(str(c)[::-1]) == c: 
        print c 
    a = a-1                         #decrement the value of a 
    c=a*b                           #multiply a by the decremented a 
    if int(str(c)[::-1]) == c: 
        print c 
 
    b = b-1                         #decrement b so that both a and b have been decremented 

结果出现了 698896、289982、94249、69696...,其中 698896 是第一个数字。目前我仍在努力弄清楚我遗漏了什么。

请您参考如下方法:

您不能以交替方式递减 a 和 b,因为这样您会丢失像 a = 999 和 b = 997 这样的值对。

改为尝试嵌套循环,从 999 开始向后数。

有点像

def is_pal(c): 
    return int(str(c)[::-1]) == c 
 
maxpal = 0 
for a in range(999, 99, -1): 
    for b in range(a, 99, -1): 
        prod = a * b 
        if is_pal(prod) and prod > maxpal: 
            maxpal = prod 
 
print maxpal 

编辑:根据 Paul 的评论修改了下限。