两个 3 位数乘积的回文
我想找到两个三位数相乘所得到的最大回文数。
我开始时 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 是第一个数字。目前我仍在试图找出我错过了什么。
I want to find the largest palindrome that can be obtained through the multiplication of two 3-digit numbers.
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您不能以交替的方式递减
a
和b
,因为这样您会丢失像 a = 999 和 b = 997 这样的值对。尝试使用嵌套循环,从 999 开始向后计数。
类似
编辑:保罗评论后修改下限。
You cannot decrement
a
andb
in an alternating fashion, because you're missing value pairs like a = 999 and b = 997 that way.Try nested looping instead, starting from 999 and counting backwards.
Something like
EDIT: Modified lower bounds after Paul's comment.
你的算法是错误的。您需要测试 a 的所有值到 b 的所有值,这可以通过使用两个循环(外部循环 a 和内部循环 b)来解决。我还建议您使用 a 和 b 作为循环索引,这可以简化逻辑(更容易记住)。
考虑将回文检查也移至其自己的函数中,以使代码更易于理解。
我不是 Python 程序员,但这是我的 PHP 解决方案:
You algorithm is wrong. You will need to test all values of a to all values of b, which can be solved by using two loops (the outer for a and the inner for b). I also suggest that you use a and b as loop indices, which simplifies the logic (makes it easier to keep in head).
Consider moving the palindrome check to it's own function as well, to make the code easier to understand.
I'm no Python programmer, but here's my solution in PHP:
最快的方法是从最大值999x999=998001之前的最大回环处循环下来。 997799,996699,..并检查每个是否可以在100..999范围内分为A和B。我的代码花了 2200 个周期。您的代码将需要大约 4K 到 8K 周期。
结束子
The fastest method is to cicle down from the biggest polindrome before maximum value 999x999=998001. 997799,996699,.. and check each if it can be divided into A and B in range 100..999. My code took 2200 cycles. Your code will take about 4K to 8K cycles.
End Sub
在 C# 中 - 要点中的解决方案 - https://gist.github.com/4496303
公共类工作者
{
公职人员(){
In C# - solution in gist - https://gist.github.com/4496303
public class worker
{
public worker(){
我做到了,并优化并减少了搜索时间的步骤数
0.03525909700010743
palindrome = 906609
count = 3748
i = 913
j = 993
I did it and have optimized and reduced the number of steps for search
time 0.03525909700010743
palindrome = 906609
count = 3748
i = 913
j = 993