题目:
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
算法:
#!/usr/bin/env python
#coding=utf-8
def check(a):
for i in xrange(999,99,-1):
if a%i==0 and 100<a/i<999:
return True
return False
a = 999999
lst = [1100,10010,100001]
for i in xrange(0,10):
for j in xrange(0,10):
for k in xrange(0,10):
a -= lst[0]*k + lst[1]*j + lst[2]*i
if check(a):
print a
exit()
else:
a = 999999
结果: 906609
算法很简单,但是我还是想解释一下,毕竟也是比较了几种方法后才选择的这个。
比较容易想到的方法就是从大往小左判断,看看是不是一个回文数,然后看看是不是两个三位数的乘积,还有就是直接找两个三位数相乘看看是不是回文数。这两种算法的效率都不高,或者说很低。
这个算法是先找一个回文数,然后利用回文数找回文数,再判断这个数是不是两个三位数的乘积。两个三位数相乘能得到最大的数是一个六位数,而六位数中最大的回文数就是999999,这个数减去1100,10010,100001后还是回文数。就利用这个规律找到下一个比999999小的回文数,判断是不是两个三位数的乘积,就得到最终结果。