我試圖找到兩個3位數的乘積的最大回文。我的客人是迴文的形式爲abccba
,所以我會循環每個數字,並停在最大的數字,這是兩個3位數字的乘積。Python中的嵌套循環
這段代碼
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'並檢查數字是否是迴文。 – 2013-02-09 09:30:11
謝謝。我提供了答案,所以他們給了我一個解決方案。我現在正在閱讀它,它也表明你提到了什麼。 – 2013-02-09 09:34:15