Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8190
  • 博文数量: 6
  • 博客积分: 161
  • 博客等级: 入伍新兵
  • 技术积分: 70
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-02 12:56
文章分类

全部博文(6)

文章存档

2017年(1)

2014年(1)

2011年(1)

2010年(3)

我的朋友
最近访客

分类: Python/Ruby

2014-10-25 18:20:26


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.

以下迭代序列定义在整数集合上:

→ n/2 (当n是偶数时)
→ 3n + 1 (当n是奇数时)

应用以上规则,并且以数字13开始,我们得到以下序列:

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

可以看出这个以13开始以1结束的序列包含10个项。虽然还没有被证明(Collatz问题),但是人们认为在这个规则下,以任何数字开始都会以1结束。

以哪个不超过100万的数字开始,能给得到最长的序列?
注意:
 一旦序列开始之后,也就是从第二项开始,项是可以超过100万的。

点击(此处)折叠或打开

  1. import time
  2. time_s=time.time()
  3. d={1:1,2:2}
  4. for x in range(1,1000000):
  5.     y=x
  6.     count_x=0
  7.     while x!=1:
  8.         if x in d:
  9.             count_x+=d[x]
  10.             d[y]=count_x
  11.             break
  12.         if x%2==0:
  13.             x/=2
  14.         else:
  15.             x=x*3+1
  16.         count_x+=1
  17. max_1=max(d.values())
  18. d=dict(map(lambda t:(t[1],t[0]), d.items()))
  19. print d[max_1]
  20. print time.time()-time_s

结果:837799
阅读(330) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~