答案 0 :(得分:2)
您可以将中间值存储在字典中并进行一种动态编程。
numbers = {1:0}
max = -1
startMax = -1
for i in range(2, 1000 000):
n = i
steps = 0
while n>=i:
if n&2 == 0:
n = n/2
else:
n = 3*n + 1
steps = steps + 1
# n < i, hence it must already be stored in the dictionary
steps = steps + numbers[n]
if steps > max:
max = steps
startMax = i
numbers[i] = steps
return startMax
另一种方法可能是存储您遇到的每个号码,并始终检查您当前所在的号码是否在地图中。但我想这可能需要更长的时间来查看这么多字典:
numbers = {1:0}
max = -1
for i in range(2, 1000 000):
if i in numbers:
steps = numbers[i]
else:
n = i
steps = 0
found = False
while not found:
if n&2 == 0:
n = n/2
else:
n = 3*n + 1
if n in numbers:
steps = numbers[n]
found = True
else:
newNumbers.append(n)
# Store all the new numbers into the dictionary
for num in newNumbers:
steps = steps + 1
numbers[num] = steps
if steps>max:
max = steps
startMax = i
return startMax
你可能想做一些测试,找出哪一个更好,但我的赌注将在第一个。
答案 1 :(得分:-1)
pypy是“打开优化的python”。
在此处获取: http://pypy.org/download.html#default-with-a-jit-compiler
要使用它,只需在您通常写pypy
的地方写python
即可。它非常兼容。主要区别在于为python编写的基于C的扩展在pypy中不起作用,尽管很多人都在努力解决这个问题。
我觉得有必要为我的答案辩护。鉴于这个非常简单的蛮力解决方案:
"Solve Project-Eueler #14"
from collections import namedtuple
Chain = namedtuple('Chain', 'length, start')
def calculate_chain(i):
start = i
length = 1
while i != 1:
length += 1
if i & 1: # `i` is odd
i = 3 * i + 1
else:
# Divide by two, efficiently.
i = i >> 1
return Chain(length, start)
def find_largest_chain(maxint):
largest_chain = Chain(0, 0)
for i in xrange(1, maxint+1):
chain = calculate_chain(i)
if chain > largest_chain:
largest_chain = chain
return largest_chain
def commandline_interface():
from sys import argv
maxint = int(argv[1])
print find_largest_chain(maxint)
if __name__ == '__main__':
commandline_interface()
python中的运行时间为23秒:
$ /usr/bin/time python 10177836.py 999999
Chain(length=525, start=837799)
22.94user 0.04system 0:23.09elapsed 99%CPU (0avgtext+0avgdata 15648maxresident)k
0inputs+0outputs (0major+1109minor)pagefaults 0swaps
并且在pypy中它是0.93秒:
$ /usr/bin/time ~/packages/pypy-1.8/bin/pypy 10177836.py 999999
Chain(length=525, start=837799)
0.66user 0.10system 0:00.93elapsed 81%CPU (0avgtext+0avgdata 63152maxresident)k
48inputs+0outputs (1major+4194minor)pagefaults 0swaps
使用特定算法,简单地使用pypy可以提高2373%的速度。我认为没有理由认为OP不会在他自己的代码中看到类似的改进。