未验证 提交 e835e968 编写于 作者: M Maxim Smolskiy 提交者: GitHub

Improve Project Euler problem 014 solution 1 (#5747)

* Improve solution

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

* Fix
上级 b6eb448e
...@@ -25,9 +25,8 @@ def solution(n: int = 1000000) -> int: ...@@ -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: ...@@ -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: ...@@ -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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册