Project Euler 014 & 015

题目14:找出以100万以下的数字开始的最长序列。

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

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

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

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

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

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

 

3n+1问题。

View Code
 1 maxn = 1000000
 2 length = [0 for i in range(maxn + 1)]
 3 length[1] = 1
 4 
 5 def count(k):
 6     counter = 0
 7     und = k
 8     while und >= k:
 9         if und % 2:
10             und = 3*und + 1
11         else:
12             und /= 2
13         counter += 1
14     counter += length[und]
15     return counter
16 
17         
18 
19 def pe014():
20     maxStartNum = 1
21     for i in range(2, maxn+1):
22         length[i] = count(i)
23         if length[i] > length[maxStartNum]:
24             maxStartNum = i
25     print(maxStartNum, max(length))
26 
27 if __name__ == '__main__':
28     pe014()
29     

 

 

题目15:从20*20的网格的左上角通往右下角有多少条路?

从一个2×2网格的左上角开始,有6条(不允许往回走)通往右下角的路。

 

对于20×20的网格,这样的路有多少条?

 

1.递归的思路,每一步都生成两种子情况。用下动态编程。

View Code
 1 grid = {}
 2 def routes(x, y):
 3     if grid.get((x,y),0):
 4         return grid[(x,y)]
 5     elif x == 0 or y == 0:
 6         grid[(x,y)] = 1
 7         return 1
 8     else:
 9         grid[(x,y)] = routes(x-1,y) + routes(x,y-1)
10         return grid[(x,y)]
11 
12 if __name__ == '__main__':
13     print(routes(20,20))

 

2.总共40步,20左20下。用组合排列就是40取20。

from math import factorial
print(factorial(40) / (factorial(20)**2))

 

题目来源:

Project Euler: http://projecteuler.net/

PE中文站:http://pe.spiritzhang.com/index.php

 

 

posted @ 2012-12-10 16:51  river_run  阅读(268)  评论(0编辑  收藏  举报