Project Euler 14 Longest Collatz sequence

Question

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.

Analysis

  1. 为了简化计算,应该将已经计算过的值所需的步数保存在一个字典里面,这样越到后面计算起来越方便。
  2. 初始值可以设在500000,因为对于任意小于500000的数n,必然有2n < 1000000的长度大于n
  3. 递归的使用
  4. 官方思路

Program

box = {1: 1}
result = 0
max = 0


def Collatz(num):
    if num in box.keys():
        return box[num]
    elif num % 2 == 0:
        step = Collatz(num / 2) + 1
    else:
        step = Collatz((3 * num + 1) / 2) + 2
    box[num] = step
    return step


for i in range(500000, 899999):
    step = Collatz(i)
    if step > max:
        result = i
        max = step

print(result)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,949评论 0 23
  • 这个周末,已经是连续被排满的第三个周末,家事、公事、私事不断的接踵而至,就像每个周都被工作排满一样。越是忙,越会忙...
    李嘟比阅读 168评论 0 0
  • 尊敬的教委领导: 我7月3号在XH小学参加期末监考,被人诬陷说在考场上骂该校老师及吓唬学生,并派领导调查此事,我觉...
    蝴蝶花间舞阅读 1,282评论 18 25
  • 1、打包时测试类异常 常见error: Failed to execute goal org.apache.mav...
    codingJanson阅读 350评论 0 0