Searching for python prime numbers generator, I found:
def primes(n):
if n==2: return [2]
elif n<2: return []
s=range(3,n+1,2)
mroot = n ** 0.5
half=(n+1)/2-1
i=0
m=3
while m <= mroot:
if s[i]:
j=(m*m-3)/2
s[j]=0
while j<half:
s[j]=0
j+=m
i=i+1
m=2*i+3
return [2]+[x for x in s if x]
print primes(13)
print primes(3000)
and also:
def get_primes(number):
while True:
if is_prime(number): #is_prime is defined somewhere else
yield number
number += 1
What's more efficient, return a list or the yield command? Why? Consider I'm looking for a very large amount of primes numbers, like first 1000 primes. By the way, the second code seems to be an infinite loop, how to stop it?
Thanks and sorry for so many questions.