Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator function for prime numbers [duplicate]

I'm trying to write a generator function for printing prime numbers as follows

 def getPrimes(n):
    prime=True
    i=2
    while(i<n):
        for a in range(2,i):
            if(i%a==0):
                prime=False
                break
        if(prime):    
            yield i

However I'm not getting the desired results p=getPrimes(100) should give me a generator function that will iterate primes from 2 through 100 but the result I'm getting is [2,3]. What am I doing wrong?

like image 351
sarath joseph Avatar asked Sep 07 '14 03:09

sarath joseph


4 Answers

Sieve of Eratosthenes: Most efficient prime generator algorithm

Taken from here:

Simple Prime Generator in Python - an answer by Eli Bendersky.

enter image description here

It marks off all the multiples of 2, 3, 5, 7 and 11. The rest are all prime numbers.

def genprimes(limit): # derived from 
                      # Code by David Eppstein, UC Irvine, 28 Feb 2002
    D = {}            # http://code.activestate.com/recipes/117119/
    q = 2

    while q <= limit:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        q += 1

p = genprimes(100)
prms = [i for i in p]

print prms

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
like image 176
Weafs.py Avatar answered Oct 23 '22 22:10

Weafs.py


You need to reset prime to True as the first statement inside the while block, not before it. As it is, once you hit a single composite number, prime will never be true again, so you'll never yield any more numbers.

like image 27
Lily Chung Avatar answered Oct 23 '22 21:10

Lily Chung


You have a couple of errors, see the comments:

def getPrimes(n):
    i = 2
    while i < n :
        prime = True # reset the `prime` variable before the inner loop
        for a in xrange(2, i):
            if i%a == 0:
                prime = False
                break
        if prime:    
            yield i
        i += 1 # don't forget to advance `i`

Now for a better implementation that handles correctly the edge cases, performs a great deal less iterations and generates a sequence of the prime numbers less than the value of the n parameter:

def getPrimes(n):
    if n <= 2:
        raise StopIteration
    yield 2
    for i in xrange(3, n, 2):
        for x in xrange(3, int(i**0.5)+2, 2):
            if not i % x:
                break
        else:
            yield i

Either way, the code works as expected:

[x for x in getPrimes(20)]
=> [2, 3, 5, 7, 11, 13, 17, 19]
like image 41
Óscar López Avatar answered Oct 23 '22 20:10

Óscar López


def isprime(n):
    for i in range(2 ,int((n**0.5))+1):
        if n % i == 0:
            return False
    return True

def getPrimes(n):
    yield 2
    i = 1
    while i <= n-2:
        i += 2
        if isprime(i):
            yield i
like image 23
beviniy Avatar answered Oct 23 '22 20:10

beviniy