Jackpotjoy

## Project Euler Question 14

### Question:

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

n $\rightarrow$n/2 (n is even)
n $\rightarrow$ 3n + 1 (n is odd)

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

13 $\rightarrow$ 40 $\rightarrow$ 20 $\rightarrow$10 $\rightarrow$ 5 $\rightarrow$ 16 $\rightarrow$ 8 $\rightarrow$ 4 $\rightarrow$ 2 $\rightarrow$ 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.

### Optimization

Acutally ,there are some optimization in this computation , such as  , there may be a number N after some chain process were reduce to a smaller number Nt, but Nt had been calculate before, we save have y elements in sequence . then we just need to add up elements between N and Nt and y,it is unnecessary to calculate Nt again .

### Code in Python

Important thing is , sort the tuple in Python , requires a key function to determine which element used as a key in sorting .

def len_iter(n):
c = 0
while n <> 1:
if n % 2 == 0:
n = n / 2
else:
n = 3*n + 1
c = c + 1
return c

rsl =   [ (i,len_iter(i)) for i in range(100,1000000) ]

new_rsl = sorted(rsl, key =lambda x: x[1], reverse = True )
print new_rsl[:5]