题目:
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk Pj| is minimised; what is the value of D?
。。。无语了。。做了一下午了。。。。。。。真无语了。。最后百度了,还调试了好久才对的。。汗了。
__author__ = 'Administrator'
import math
import time
t=time.time()
def func(n):return n*(3*n-1)/2
def isPentagonal(n):
floatnum=(math.sqrt(24*n+1)+1)/6.0
return floatnum==int(floatnum)
#return isinstance((math.sqrt(24*n+1)+1)/6.0,int)
sourcelist=[12,22]
futurelist=[]
pairlist=[]
index=5
s,e=0,0
#print 1.0+2
print func(1020)
print isPentagonal(func(2167)-func(1020)),isPentagonal(func(2167)+func(1020))
#print func(1020),func(2067)
flag=False
while 1:
if flag==True:
break
newnum=func(index)
if newnum<sourcelist[-1]*2:
for oldnum in sourcelist[::-1]:
if isPentagonal(newnum-oldnum):
if isPentagonal(newnum+oldnum):
pairlist.append((oldnum,newnum,oldnum+newnum))
flag=True
break
elif isPentagonal(2*newnum-oldnum):
pairlist.append((newnum-oldnum,newnum,2*newnum-oldnum))
flag=True
break
#pairlist.sort(key=lambda x:x[2])
sourcelist.append(newnum)
index+=1
print pairlist[0][1]-pairlist[0][0]
print time.time()-t
结果为:
1560090
True True
5482660
2.39400005341
牛人的代码为:
starttime = time.time()
pSet = set()
dictionary = {}
n = 0
p = 0
while 1:
p += 3 * n + 1
if dictionary.has_key(p):
print dictionary[p]
break
for old in pSet:
diff = p - old
if diff in pSet:
dictionary[p + old] = diff
pSet.add(p)
n += 1
print "time:",time.time()-starttime
运行结果为:
5482660
time: 0.639999866486
连一秒都不需要。。真的是太NB了。。