a better prime number generator

Brian Zhou brian_zhouNOSPAM at techie.com
Mon Oct 22 16:03:27 EDT 2001


# A little improvement.

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

"Brian Zhou" <brian_zhou at NOSPAMtechie.com> wrote in message
> 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
> news:23d58b26.0110210939.55bb7e0c at posting.google.com...
> > 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
>
>
>





More information about the Python-list mailing list