0

我试图找到最大的回文数,它是两个 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,这是正确的。

我不知道我哪里错了。

4

2 回答 2

4
xrange(1, 9) == (1, 2, 3, 4, 5, 6, 7, 8)

xrange(start, stop, step)生成从startto (但不包括)stop的所有数字,步长为step.

xrange(5) == (0, 1, 2, 3, 4)
xrange(1, 5) == (1, 2, 3, 4)
xrange(1, 5, 2) == (1, 3)

您也可以将xrange(1, 10)其包含9在范围内。

于 2013-02-09T09:13:17.773 回答
2

只有(大约)50 万对 3 位数字,因此对它们进行测试更快更简单。

def palindrome_3products():
    for i in xrange(100, 1000):
        for j in xrange(i, 1000):
            if str(i * j) == str(i * j)[::-1]:
                yield i * j, i, j

print max(palindrome_3products())
于 2013-02-09T09:47:16.993 回答