Project Euler Problem #14 Solution
We calculate the length of each Collatz sequence with starting number and find the value of n for which the length is maximum.
Note that we actually calculate one less than the length of each sequence, but since that subtraction is applied to each length, it doesn’t matter.
def is_even(n): return n % 2 == 0 def collatz_length(n): length = 0 while n > 1: length += 1 if is_even(n): n /= 2 else: n = 3 * n + 1 return length max_n = 0 max_len = 0 for n in range(1, 1000000): len = collatz_length(n) if len > max_len: max_len = len max_n = n print max_n
Advertisement
