# a better prime number generator

Brian Zhou brian_zhou at NOSPAMtechie.com
Mon Oct 22 08:27:38 CEST 2001

```The one comes with python source Demo/scripts/primes.py should be very fast.
But just for fun, here is one more, using recursion and list comprehension:

def primes(max):
def sieve(l):
if l[0] ** 2 > max: return l
x = l.pop(0)
return [x] + sieve([y for y in l if y % x != 0])
return sieve([2] + range(3, max + 1, 2))

-Brian

"Rupendra Dhillon" <dhillon_rs at rediffmail.com> wrote in message
> hi all,
> I have just been introduced to pyton and find it a very good ( takes
> off all the bookwork ) language. I was trying to develope a ast prime
> number generator. I designed the following algo. Can you please
> suggest a faster one or modifications to this only to make it faster
>
> #the following algo returns all the primes below x
>
> def getPrimesTill(x):
> a = range(2,x)
> c = [2]
>
> i = 0
> j = 0
>
> foundone = 1
>
> while i < len(a):
> while j < len(c) and (c[j] < (.5 * a[i]) ) and foundone == 1:
> if a[i]%c[j] == 0:
> foundone = 0
> j = j + 1
> if foundone == 1 and i > 0:
> c.append(a[i])
> j = 0
> foundone = 1
> i = i + 1
> return c
>
>
> roop

```