Just use recursion and cache. Python has the decoration @lru_cache, which autoimplements caching to a recursive function. Runs in 2.304 seconds
The function should look something like:
from functools import lru_cache
@lru_cache(maxsize=None)
def collatz(x):
if x == 1:
return 1
if x % 2 == 0:
return 1 + collatz(x // 2)
return 1 + collatz(3*x + 1)
if you want to do it without the decoration:
cache = {}
def collatz(x):
global cache
if x in cache:
return cache[x]
if x == 1:
return 1
if x % 2 == 0:
result = 1 + collatz(x // 2)
else:
result = 1 + collatz(3*x + 1)
cache[x] = result
return result
here's the main code:
maxChain = 0
maxNumber = 0
for i in range(1, 1000001):
chainSize = collatz(i)
if chainSize > maxChain:
maxChain = chainSize
maxNumber = i
print(maxNumber)