`

Project Euler 第14题

阅读更多
迭代序列
The following iterative sequence is defined for the set of positive integers:

n  n/2 (n is even)
n  3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13  40  20  10  5  16  8  4  2  1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

找出1,000,000以内,迭代次数最多的数。
分享到:
评论
2 楼 lzzzing 2010-08-05  
import time
d = {1:1}
maxv,maxn = 0,0
for i in xrange(2,1000000):
    if not d.has_key(i):
        c = make(i)
        if c > maxv: maxv,maxn = c,i
def make(n):
    if not d.has_key(n):
        print n
        if n % 2 == 1:
            d[n] = 1 + make(n*3+1)
        else:
            d[n] = 1 + make(n/2)
    return d[n]
        

start = time.time()
print maxn,maxv
print time.time() - start
1 楼 lampeter123 2009-08-12  
def sequenceNum(n):
    seq=[]
    while(n!=1):
        seq.append(n)
        n = n%2==0 and n/2 or 3*n+1
    seq.append(1)
    return seq

if __name__ == "__main__":
    maxlen = 0
    for i in xrange(1000000):
        l = sequenceNum(i)
        if (len(l)>maxlen):
            maxlen = len(l)
            m=i

    print maxlen
    print m

相关推荐

Global site tag (gtag.js) - Google Analytics