来自两个3位数的乘积的回文 [英] Palindrome from the product of two 3-digit numbers

查看:80
本文介绍了来自两个3位数的乘积的回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到可以通过将两个3位数相乘得到的最大回文.

I want to find the largest palindrome that can be obtained through the multiplication of two 3-digit numbers.

我首先将a和b都设为999,然后将发生的每个乘法都减小a和b.

I started off with a and b both being 999, and to decrement a and b with every multiplication that occurred.

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是第一个数字.目前,我仍在尝试找出我所缺少的内容.

The result has turned up 698896, 289982, 94249, 69696... with 698896 being the first number. Currently I'm still trying to figure out what I'm missing.

推荐答案

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

You cannot decrement a and b in an alternating fashion, because you're missing value pairs like a = 999 and b = 997 that way.

请改用嵌套循环,从999开始并向后计数.

Try nested looping instead, starting from 999 and counting backwards.

类似

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

保罗发表评论后修改了下界.

Modified lower bounds after Paul's comment.

这篇关于来自两个3位数的乘积的回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆