Longest Collatz sequence
First read the problem description.
We’ll use memoization to cache results for odd numbers. We don’t cache even numbers since there’s a separate loop that divides even numbers by 2 until we have an odd number. By storing only half of the numbers we also halve the amount of memory needed.
= {}
cache def total_stopping_time(n):
= n
t = 0
c while True:
while t % 2 == 0:
//= 2
t += 1
c if t == 1:
break
if cache.get(t):
+= cache.get(t)
c break
= (3*t + 1)
t += 1
c
if n % 2 != 0:
= c
cache[n] return c
= 0
max_n = 0
max_length for n in range(1, 1_000_000):
= total_stopping_time(n)
length if length > max_length:
= length
max_length = n
max_n max_n
837799
Source code of the solution(s):