Here is what I have:
def is_prime(num):
if num < 2: return False
elif num < 4: return True
elif not num % 2: return False
elif num < 9: return True
elif not num % 3: return False
else:
for n in range(5, int(math.sqrt(num) + 1), 6):
if not num % n:
return False
elif not num % (n + 2):
return False
return True
It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.
Now if you want to generate a list of primes, you can do:
# primes up to 'max'
def primes_max(max):
yield 2
for n in range(3, max, 2):
if is_prime(n):
yield n
# the first 'count' primes
def primes_count(count):
counter = 0
num = 3
yield 2
while counter < count:
if is_prime(num):
yield num
counter += 1
num += 2
using generators here might be desired for efficiency.
And just for reference, instead of saying:
one = 1
while one == 1:
# do stuff
you can simply say:
while 1:
#do stuff