Improve Project Euler problem 014 solution 1 (#5747)

* Improve solution

* Uncomment code that has been commented due to slow execution affecting Travis

* Fix
This commit is contained in:
Maxim Smolskiy 2021-11-04 18:37:47 +03:00 committed by GitHub
parent b6eb448e63
commit e835e96856
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -25,9 +25,8 @@ def solution(n: int = 1000000) -> int:
n n/2 (n is even) n n/2 (n is even)
n 3n + 1 (n is odd) n 3n + 1 (n is odd)
# The code below has been commented due to slow execution affecting Travis. >>> solution(1000000)
# >>> solution(1000000) 837799
# 837799
>>> solution(200) >>> solution(200)
171 171
>>> solution(5000) >>> solution(5000)
@ -35,14 +34,18 @@ def solution(n: int = 1000000) -> int:
>>> solution(15000) >>> solution(15000)
13255 13255
""" """
largest_number = 0 largest_number = 1
pre_counter = 0 pre_counter = 1
counters = {1: 1}
for input1 in range(n): for input1 in range(2, n):
counter = 1 counter = 0
number = input1 number = input1
while number > 1: while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0: if number % 2 == 0:
number //= 2 number //= 2
counter += 1 counter += 1
@ -50,6 +53,9 @@ def solution(n: int = 1000000) -> int:
number = (3 * number) + 1 number = (3 * number) + 1
counter += 1 counter += 1
if input1 not in counters:
counters[input1] = counter
if counter > pre_counter: if counter > pre_counter:
largest_number = input1 largest_number = input1
pre_counter = counter pre_counter = counter