1. 程式人生 > >尤拉專案004:尋找最大的迴文數

尤拉專案004:尋找最大的迴文數

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.

尋找有兩個三位數相乘的最大回文數

我的python程式碼如下:

#method1:
def reverse(s):
    return s[::-1]
maxPalindromic = 0 
for i in range(100,999):
    for j in range(i,999):
        s = str(i*j)
        if s == reverse(s):
            if int(s)>maxPalindromic:
                maxPalindromic = int(s)
print maxPalindromic
#method2:
def reverse(s):
    return s[::-1]
def canBeDivide(num):
    for i in range(100,1000):
        if num%i==0 and num/i<1000:
            return True
    return False
def findMaxPalindromic():            
    for x in range(9,0,-1):
        for y in range(9,-1,-1):
            for z in range(9,-1,-1):
                num = 100001*x+10010*y+1100*z
                if canBeDivide(num):
                    return num
print findMaxPalindromic()
                    
                
方法一,比較直觀,容易理解;

方法二,效率高。

有不懂得或者有更好的想法,可以留言,互相學習啊!