[英]Python is taking a very long time to execute code
我正在使用PyCharm社区2018。我试图找到1到200万之间的素数之和,这是我的代码。
primes = [x for x in range (1,2000000) if all (x%y!=0 for y in range (2,x))]
total = 0
for x in primes:
total = total + x
print (total)
已经20分钟了,我仍然没有输出。 您是否有任何建议使其运行速度更快,或者我的方法有误?
这很可能是因为您找到质数的方法效率低下并且范围太大。
您的算法是查找质数的一种蛮力方法,其时间复杂度为O(n²)。 如果将算法的时间设为较小的数字,则会看到随着n
增加,花费的时间不会线性增加,但实际上是二次的。
+--------+---------------+
| n | time(in sec) |
+--------+---------------+
| 1000 | 0.007979 |
| 2000 | 0.038865 |
| 5000 | 0.137037 |
| 10000 | 0.499688 |
| 20000 | 1.892315 |
| 50000 | 10.29843 |
| 100000 | 1374.101 |
| ... | ... |
+--------+---------------+
我建议您看一下Eratosthenes筛 。 如果您搜索此语言,则将以所需的任何语言找到它的许多实现 。
我建议使用多重处理来加快您的代码
from multiprocessing import Pool
def find_prime(n):
#code to determine prime number here
#return 0 if it is not prime or the number if it is
pool=Pool()
total=sum(pool.map(find_prime,range(1,2000000))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.