码迷,mamicode.com
首页 > 编程语言 > 详细

欧拉计划(python) problem 14

时间:2015-01-27 13:33:21      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

Longest Collatz sequence

Problem 14

The following iterative sequence is defined for the set of positive integers:

nn/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.


Answer:
837799
Completed on Tue, 27 Jan 2015, 02:57

def func1(x):
    if x%2==0:
        return x/2
    else:
        return 3*x+1

dict={}
def func2(x):
    x=func1(x)
    if x==1:
        return 2
    rest=dict.get(x)
    if rest!=None:
        return rest+1
    else:
        result=func2(x)+1
        dict[x]=result
        return result

value=0
k=0
for i in range(1,1000000):
    temp=func2(i)
    if temp>k:
        k=temp
        value=i
        
print(value)


time : 3s

欧拉计划(python) problem 14

标签:

原文地址:http://blog.csdn.net/zhangzhengyi03539/article/details/43192155

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!