问题:
Returns an answer in 0.016 secs.
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 pro_palin (n):
s_str='{0}'.format(n)
d_str=s_str[::-1]
sum=0
n_len=len(s_str)
for i in d_str :
sum=sum*10+int(i)
return n*10**(n_len)+sum
def ismatched (n,index):
divisor=2
product=1
while product!=n:
print n,product
if n/(10**(index-1))>0 and n/(10**(index-1))<10 and product/(10**(index-1))>0 and product/(10**(index-1))<10:
print n,product
return True
while n%divisor==0:
if n/(10**(index-1))>0 and n/(10**(index-1))<10 and product/(10**(index-1))>0 and product/(10**(index-1))<10:
print n,product,
return True
product*=divisor
n=n/divisor
divisor+=1
return False
############主程序################
if __name__=='__main__':
ra=range(900,1000)[::-1]
#print ra
"""
for item in ra :
pralindro=pro_palin(item)
#print pralindro
if ismatched(pralindro,3):
print item
"""
print ismatched(9009,2)
有问题找不到,99*91所以,我这肯定有问题。
我最终的代码
a
def pro_palin (n):
s_str='{0}'.format(n)
d_str=s_str[::-1]
sum=0
n_len=len(s_str)
for i in d_str :
sum=sum*10+int(i)
return n*10**(n_len)+sum
def ismatched (n,index):
divisor=2
product=1
ra=range(10**(index-1),10**index)[::-1]
for i in ra :
a,remain=divmod(n,i)
if remain==0 and a/10**(index-1)>0 and a/10**(index-1)<10:
print i,a
return True
return False
############主程序################
if __name__=='__main__':
ra=range(900,1000)[::-1]
#print ra
for item in ra :
pralindro=pro_palin(item)
#print pralindro
if ismatched(pralindro,3):
print pralindro
print ismatched(9009,2)
别人牛人的解答:
The palindrome can be written as:abccbaWhich then simpifies to:100000a + 10000b + 1000c + 100c + 10b + aAnd then:100001a + 10010b + 1100cFactoring out 11, you get:11(9091a + 910b + 100c)So the palindrome must be divisible by 11. Seeing as 11 is prime, at least one of the numbers must be divisible by 11. So brute force in Python, only with less numbers to be checked:
Python |
Hide Code
|
def c():
max = maxI = maxJ = 0
i = 999
j = 990
while (i > 100):
j = 990
while (j > 100):
product = i * j
if (product > max):
productString = str(product)
if (productString == productString[::-1]):
max = product
maxI = i
maxJ = j
j -= 11
i -= 1
return max, maxI, maxJ