44Pentagon numbers Problem 44

来源:互联网 发布:巨人网络怎么样 知乎 编辑:程序博客网 时间:2024/06/05 06:07

题目:

Pentagonal numbers are generated by the formula, Pn=n(3n−1)/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 mathimport timet=time.time()def func(n):return n*(3*n-1)/2def 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=5s,e=0,0#print 1.0+2print func(1020)print isPentagonal(func(2167)-func(1020)),isPentagonal(func(2167)+func(1020))#print func(1020),func(2067)flag=Falsewhile 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+=1print pairlist[0][1]-pairlist[0][0]print time.time()-t
结果为:

1560090
True True
5482660
2.39400005341
牛人的代码为:

starttime = time.time()pSet = set()dictionary = {}n = 0p = 0while 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 += 1print "time:",time.time()-starttime
运行结果为:
5482660
time: 0.639999866486
连一秒都不需要。。真的是太NB了。。


0 0