Refactor problem
This commit is contained in:
@@ -12,14 +12,14 @@ https://projecteuler.net/problem=14
|
|||||||
from project_euler_python.utils import timeit
|
from project_euler_python.utils import timeit
|
||||||
|
|
||||||
|
|
||||||
def chain_length(n, terms):
|
def chain_length(n: int, terms: dict[int, int]) -> int:
|
||||||
length = 0
|
length = 0
|
||||||
while n != 1:
|
while n != 1:
|
||||||
if n in terms:
|
if n in terms:
|
||||||
length += terms[n]
|
length += terms[n]
|
||||||
break
|
break
|
||||||
if n % 2 == 0:
|
if n % 2 == 0:
|
||||||
n = n / 2
|
n //= 2
|
||||||
else:
|
else:
|
||||||
n = 3 * n + 1
|
n = 3 * n + 1
|
||||||
length += 1
|
length += 1
|
||||||
@@ -27,7 +27,7 @@ def chain_length(n, terms):
|
|||||||
|
|
||||||
|
|
||||||
@timeit("Problem 014")
|
@timeit("Problem 014")
|
||||||
def compute():
|
def compute() -> int:
|
||||||
"""
|
"""
|
||||||
The following iterative sequence is defined for the set of positive
|
The following iterative sequence is defined for the set of positive
|
||||||
integers:
|
integers:
|
||||||
@@ -49,15 +49,17 @@ def compute():
|
|||||||
NOTE: Once the chain starts the terms are allowed to go above one million.
|
NOTE: Once the chain starts the terms are allowed to go above one million.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
ans = 0
|
|
||||||
limit = 1_000_000
|
limit = 1_000_000
|
||||||
score = 0
|
ans = 0
|
||||||
terms = dict()
|
longest_length = 0
|
||||||
for i in range(1, limit):
|
chain_lengths = {1: 0}
|
||||||
terms[i] = chain_length(i, terms)
|
|
||||||
if terms[i] > score:
|
for start in range(2, limit):
|
||||||
score = terms[i]
|
current_length = chain_length(start, chain_lengths)
|
||||||
ans = i
|
chain_lengths[start] = current_length
|
||||||
|
if current_length > longest_length:
|
||||||
|
ans = start
|
||||||
|
longest_length = current_length
|
||||||
|
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user