我试图在Python 3.4.1中创建一个程序来获取2到100,000的素数。我怎样才能加快我的Python程序?
我的问题是,它需要太多的时间来处理所有的信息,它永远不会给我任何结果。
我已经离开了大约半个小时,它减慢了我所有的电脑,它并没有给我我想要的东西。
我正在使用Eratosthenes的筛算法"Criba de Eratostenes"。
这里是我的代码:
from math import *
def primos(num):
num2 = num + 1
tnumeros = [] # tnumeros = every number from 2 to num
npnumeros= [] # npnumeros = every number that is no prime
pnumeros = [] # pnumeros = every prime number
for a in range(2, num2):
tnumeros.append(a)
for i in range(2, int(sqrt(num)) + 1):
for j in range(i, int(num/i) + 1):
np = i * j
npnumeros.append(np)
npnumeros = list(set(npnumeros))
for e in tnumeros:
if (e in npnumeros):
continue
else:
pnumeros.append(e)
return (str("".join(str(pnumeros))))
print(primos(100000))
这个问题似乎是无关紧要的,因为它没有bug。代码评论可以在[Code Review Stack Exchange](http://codereview.stackexchange.com/)上查询。 – usr2564301 2014-10-04 17:34:40
或者,你可能会认为它有性能问题,所以它的规格失败了? – matsjoyce 2014-10-04 17:41:27
这实际上并不是Eratosthenes的Sieve:该算法同时识别素数并移除每个连续素数的倍数。在这里,您将除去每个*整数的倍数,而不仅仅是几个素数的倍数。 – 2014-10-04 18:26:34