# This Python file uses the following encoding:utf-8
# 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, we generate the following sequence:
# 13→40→20→10→5→16→8→4→2→1
# It can be seen the sequence (starting at and finishing at 1) contains terms. Although it had not been proved yet (Collatz problem), it was 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 is allowed to go above one million.
Import time
Start = Time.time ()
def chain_len (n):
Len = 1
While n! = 1:
If n% 2 = = 0:
N/= 2
Len + = 1
Else
n = 3*n + 1
Len + = 1
Return len
Max_len = 1
Max_len_num = 1
For I in xrange (1, 1000000):
If Chain_len (i) > Max_len:
Max_len = Chain_len (i)
Max_len_num = i
Print "%s produces the longest chain and cost%s seconds"% (Max_len_num, Time.time ()-start)
Euler Project question in Python