# 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 13, we generate the following sequence: # 13 40 20 10 5 16 8 4 2 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. from common import max_by from functools import lru_cache @lru_cache(maxsize=None) def chain_size(n): return 1 if n == 1 else 1 + chain_size(n // 2 if n % 2 == 0 else 3 * n + 1) print(max_by(chain_size, range(1, 1000000)))
from common import max_by from decimal import * getcontext().prec = 2000 def is_cycle(target, string, start): length = len(target) limit = len(string) for i in range(start, limit, length): if i + length > limit: return True t = string[i:i + length] if t != target: return False return True def find_cycle(string): for start in range(len(string)): for i in range(start + 1, (len(string) - start) // 2 + 1): target = string[start:i] if is_cycle(target, string, start): return target return None def cycle_len(n): cycle = find_cycle(str(Decimal(1) / Decimal(n))[2:]) r = len(cycle) if cycle else 0 return r print(max_by(cycle_len, range(2, 1000)))