Refactor problem
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user