码迷,mamicode.com
首页 > 其他好文 > 详细

projecteuler---->problem=14----Longest Collatz sequence

时间:2014-06-04 13:56:33      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:python

title:

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

n bubuko.com,布布扣 n/2 (n is even)
n bubuko.com,布布扣 3n + 1 (n is odd)

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

13 bubuko.com,布布扣 40 bubuko.com,布布扣 20 bubuko.com,布布扣 10 bubuko.com,布布扣 5 bubuko.com,布布扣 16 bubuko.com,布布扣 8 bubuko.com,布布扣 4 bubuko.com,布布扣 2 bubuko.com,布布扣 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.

翻译:

下面的循环数列是由正整数根据以下规则构成的:

nn/2 (若n是偶数)

n → 3n + 1 (若n是奇数)

若数列从13开始,就生成了如下数列:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

显然以上数列有10个数字,虽然未经证明(著名的Collatz猜想),但我们认为无论由什么数字开始,数列都会在1处结束。故数列一旦产生了1这一项,就认为数列结束。

这次的问题是:根据以上规则,由100万以下的哪个数字开始,可以产生最长的数列?

请注意:产生的数列可能会包含数字超过100万的项。

import time
def f(n):
    if n%2==1 and n>1:
       return f(3*n+1)+1
    elif n%2==0:
       return f(n/2)+1
    return 1
m,value=0,0
begin=time.time()
for i in range(1,1000000):
    tmp=f(i)
    if tmp>m:
        value=i
        m=tmp
print time.time()-begin
print m,value



projecteuler---->problem=14----Longest Collatz sequence,布布扣,bubuko.com

projecteuler---->problem=14----Longest Collatz sequence

标签:python

原文地址:http://blog.csdn.net/q745401990/article/details/28235147

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