【发布时间】:2013-02-09 09:11:34
【问题描述】:
我试图找到两个 3 位数字乘积的最大回文数。我的客人是回文将具有abccba 的形式,所以我将遍历每个数字并停在两个 3 位数字乘积的最大数字处。
这段代码
def hasLargeDivisors(n):
"""
Function to determine if a number has two divisors
greater than 99
"""
d = 999
while n / d > 99 and n / d < 999 and d > 99:
if n % d is 0:
return True
d-=1
return False
def compisitePalindrome():
"""
Function to find the largest palindrome
that is the product of 2 three-digit numbers
"""
for a in reversed(xrange(1, 9)):
for b in reversed(xrange(0, 9)):
for c in reversed(xrange(0, 9)):
num = a*100001 + b*10010 + c*1100
if hasLargeDivisors(num):
return num
return 0
产生 888888 = 962 * 924,这是不正确的。
这段代码
def hasLargeDivisors(n):
"""
Function to determine if a number has two divisors
greater than 99
"""
d = 999
while n / d > 99 and n / d < 999 and d > 99:
if n % d is 0:
return True
d-=1
return False
def compisitePalindrome():
"""
Function to find the largest palindrome
that is the product of 2 three-digit numbers
"""
a = 9
for b in reversed(xrange(0, 9)):
for c in reversed(xrange(0, 9)):
num = a*100001 + b*10010 + c*1100
if hasLargeDivisors(num):
return num
return 0
产生 906609 = 993 * 913,这是正确的。
我不知道我哪里出错了。
【问题讨论】:
-
您可以通过考虑以下事实来高度简化算法:任何回文数都可以被
11整除。所以,从11的最大倍数开始,这是两个3位数字的倍数,然后在xrange中使用-11,并检查该数字是否为回文。 -
谢谢。我已经提供了答案,所以他们给了我一个解决方案。我现在正在阅读它,它也暗示了你提到的内容。
标签: python