我已经编写了一些计算素数的代码(我不知道有什么特别的)并且正如预期的那样它会减慢数字越大,我知道无论数字如何都不可能使其速度相同但我相信我可以提高它的速度,我只是不知道如何...
import time
number = 1000000001
count = 0
start = time.time()
while number > 1000000000 and number < 10000000000000:
for i in range(1, round(number/2 + 1)):
if (number / i).is_integer():
count += 1
if count > 1:
break
if count < 2:
print(str(number) + ' prime')
number = number + 1
count = 0
end = time.time()
print(end - start)
最佳答案
几件事:
- 您不必从
1
开始检查,而是从3
、5
和所有奇数开始检查; - 您不必检查直到 n/2,但您可以在 sqrt(n) 时停止;
- 不要使用除法,因为那时你会使用 float ,但使用
%
来检查模数; - 您只需检查奇数(或两个);和
- 您可以省略 while 循环中的大于检查,因为数字只会递增。
所以一个改进的版本是:
import time
<b>from math import sqrt # import square root</b>
start = time.time()
<b>for number in range(1000000001,10000000000000,2): # use for, hops of 2</b>
<b>for i in range(3, int(sqrt(number))+1,2): # check 3, 5,... up to sqrt(n)</b>
<b>if number % i == 0: # use modulo checks instead of floating point</b>
break
<b>else: # use a for-else structure for faster ending</b>
print(str(number) + ' prime')
count = 0
end = time.time()
print(end - start)
然而,Python 并不是为了充分利用 CPU 而设计的。如果你真的想编写一个 super 优化的算法,你将不得不选择一种更快(但不太方便)的编程语言。
关于python - 我怎样才能加快这个 python 代码的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44483034/