First one is not optimised, while the second one is slightly more optimised. Of course, "Sieve of Eratosthenes" is the best. This functions produce the prime numbers in sequence, but not having an upper limit.
Simple and not optimised:
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
Slightly optimised by not checking all even number and break
out of the for loop when the number is not a prime:
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
Try measuring the 2 different runtime:
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')
Output:
Simple Prime List: 775.798 ms
Optimised Prime List: 69.48299999999996 ms