a better prime number generator

Tim H thamza.nospam at flash.net
Sun Oct 21 14:54:18 EDT 2001


I'm not sure what you are doing, didn't try to figure out how yours should
be indented, but I came up with this when I first started playing around
with python.  It is more efficient than the one in the tutorial and much
simpler to understand than yours.  There are probably better ways.

def primes(n):
    "Returns list of prime numbers 2 to n."
    p = [2]
    for a in range(3, n+1):
        for b in p:
            if a % b == 0:
                break
        else:
            p.append(a)
    return p

Tim

"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