From 24fb140672317e675c4ee7b5283e4835254a26ff Mon Sep 17 00:00:00 2001 From: daviddoji Date: Mon, 6 Apr 2026 16:01:42 +0200 Subject: [PATCH] Refactor problem --- .../problems_001_050/Problem014.py | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/project_euler_python/problems_001_050/Problem014.py b/src/project_euler_python/problems_001_050/Problem014.py index d75d253..aad3b22 100644 --- a/src/project_euler_python/problems_001_050/Problem014.py +++ b/src/project_euler_python/problems_001_050/Problem014.py @@ -12,14 +12,14 @@ https://projecteuler.net/problem=14 from project_euler_python.utils import timeit -def chain_length(n, terms): +def chain_length(n: int, terms: dict[int, int]) -> int: length = 0 while n != 1: if n in terms: length += terms[n] break if n % 2 == 0: - n = n / 2 + n //= 2 else: n = 3 * n + 1 length += 1 @@ -27,7 +27,7 @@ def chain_length(n, terms): @timeit("Problem 014") -def compute(): +def compute() -> int: """ The following iterative sequence is defined for the set of positive integers: @@ -49,15 +49,17 @@ def compute(): NOTE: Once the chain starts the terms are allowed to go above one million. """ - ans = 0 limit = 1_000_000 - score = 0 - terms = dict() - for i in range(1, limit): - terms[i] = chain_length(i, terms) - if terms[i] > score: - score = terms[i] - ans = i + ans = 0 + longest_length = 0 + chain_lengths = {1: 0} + + for start in range(2, limit): + current_length = chain_length(start, chain_lengths) + chain_lengths[start] = current_length + if current_length > longest_length: + ans = start + longest_length = current_length return ans