0

2 つの 3 桁の数の積である最大の回文を見つけようとしています。私のゲストは、回文の形式がabccbaになるということです。そのため、各桁をループして、2 つの 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)からのすべての数値を生成しますstart(ただし、を含みません) 。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

3 桁の数字のペアは (約) 50 万個しかないため、それらすべてをテストする方が迅速かつ簡単です。

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 に答える