44Pentagon numbers Problem 44

题目:

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 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了。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值