A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 X 99.
Find the largest palindrome made from the product of two 3-digit numbers.
通常解法:
def isPalindrome(n):
s = str(n)
return s == s[::-1]
def findLargestPalindrome():
largestPalindrome = 0
for a in range(100, 1000):
for b in range(100, 1000):
if isPalindrome(a*b) and a*b > largestPalindrome:
largestPalindrome = a*b
return largestPalindrome
分析:
1、每个palindromic数可以表示为:
P=100000x+10000y+1000z+100z+10y+x
P=100001x+10010y+1100z
P=11(9091x+910y+100z)
且P=ab,由每个数可以分解为N个素数的乘积。可知,a和b中至少有一个可以被11整除。
2、a*b和b*a的结果可以只计算一次。
3、从大往小计算,可以更早的发现结果。
改进算法:
def findLargestPalindrome():
largestPalindrome = 0
a = 999
while a >= 100:
if not a % 11:
b = 999
db = 1
else:
b = 990 # 990是小于1000又能够被11整除的最大数
db = 11
while b >= a:
if a * b <= largestPalindrome:
break # a和b都是从大到小遍历,相乘的结果不断变小。
if isPalindrome(a*b):
largestPalindrome = a*b
b -= db
a -= 1
return largestPalindrome