天天看點

用Python解答 ProjectEuler問題(4)

E004

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91  99.

Find the largest palindrome made from the product of two 3-digit numbers.

水仙花數是從左向右和從右向左讀都相同的自然數。求兩個三位數的乘積中最大的水仙花數。

def problem4():
    min, max = 100, 999
    def isPalindromic(num):
        if num<=10:
            return False
        digits = list(str(num))
        revdigs = list(str(num))
        revdigs.reverse()
        return digits==revdigs

    x = y = avg = max
    while avg>=min:
        num = x*y
        if isPalindromic(num):
            return x,y,num
        elif x<=min or y>=max:
            avg -= 0.5
            x = int(avg)
            y = int(avg+0.5)
        else:
            x -= 1
            y += 1


if __name__=='__main__':
    print str(problem4())
      

考慮兩個三位數乘積最大的是 999x999, (平均數999)

其次是 998x999,           (平均數998.5)

再次是 998x998, 997x999,  (平均數998)

然後是 997x998, 996x999,  (平均數997.5)

       ......