我目前正在解决欧拉计划中的问题,到目前为止,我已经为一个问题想出了这段代码。
from itertools import combinations
import time
def findanums(n):
l = []
for i in range(1, n + 1):
s = []
for j in range(1, i):
if i % j == 0:
s.append(j)
if sum(s) > i:
l.append(i)
return l
start = time.time() #start time
limit = 28123
anums = findanums(limit + 1) #abundant numbers (1..limit)
print "done finding abundants", time.time() - start
pairs = combinations(anums, 2)
print "done finding combinations", time.time() - start
sums = map(lambda x: x[0]+x[1], pairs)
print "done finding all possible sums", time.time() - start
print "start main loop"
answer = 0
for i in range(1,limit+1):
if i not in sums:
answer += i
print "ANSWER:",answer
当我运行这个程序时,我遇到了一个 MemoryError
错误。回溯信息如下:
File "test.py", line 20, in <module>
sums = map(lambda x: x[0]+x[1], pairs)
我试图通过禁用垃圾回收来防止这种情况发生,但从Google上得到的信息中我还没有成功。我这样做是错的吗?在我的脑海中,这似乎是最自然的方法,但我现在感到很困惑。
另外一提:我正在使用PyPy 2.0 Beta2(Python 2.7.4),因为它比我使用过的任何其他Python实现都要快得多,而Scipy / Numpy超出了我的能力范围,因为我还只是一个初学者,而且我没有工程或强大的数学背景。
findanums
运行之后打印len(anums)
,它会显示28123
,这意味着从1到28123的每个数字都是过剩数。我认为这不正确。 - Kevinfor j in range(1, i)
@Ofiris - Jesse Neffxrange
,这可以在我的机器上节省10秒钟的时间。 - Ofiris