第一个是没有任何优化,打破i % j
替换,而第二个稍微更优化。当然,“Sieve of Eratosthenes”是最好的。这个函数按顺序产生素数,但没有上限。
简单,没有优化:
def simple_prime_list(num):
list_of_prime = (2,)
current_num = 2
is_prime = True
while len(list_of_prime) != num:
current_num += 1
for i in list_of_prime:
if current_num % i == 0:
is_prime = False
if is_prime == True:
list_of_prime += (current_num,)
#To reset the status
is_prime = True
return list_of_prime
通过不检查所有的偶数和break
出的for循环时数是不是质略优化:
def prime_list(num):
list_of_prime = (2,)
current_num = 2
is_prime = True
while len(list_of_prime) != num:
current_num += 1
if current_num % 2 != 0:
for i in list_of_prime:
if current_num % i == 0:
is_prime = False
break
if is_prime == True:
list_of_prime += (current_num,)
#To reset the status
is_prime = True
return list_of_prime
尝试测量2不同的运行时间:
import time
def measureTime(fn):
start = time.clock()
fn()
end = time.clock()
#return value in millisecond
return (end - start)*1000
print('Simple Prime List:', measureTime(lambda: simple_prime_list(1000)), 'ms')
print('Optimised Prime List:', measureTime(lambda: prime_list(1000)), 'ms')
输出:
简单总理名单:775.798毫秒
优化总理名单:69.48299999999996毫秒
谢谢你很多! :) –
@DavidBeck,不用担心,不客气。如果你真的想要一个有效的方法来生成素数,请使用Eratosthenes的筛子http://stackoverflow.com/a/23423821/2141635 –