How do I generate list of all prime numbers in Python?

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


10 points

What is the best way to generate prime numbers in python below N.



2 points

The fasted way to generate Prime number in Python can be:

import itertools
def erat2( ):
    D = {  }
    yield 2
    for q in itertools.islice(itertools.count(3), 0, None, 2):
        p = D.pop(q, None)
        if p is None:
            D[q*q] = q
            yield q
        else:
            x = p + q
            while x in D or not (x&1):
                x += p
            D[x] = p

so that would give

get_primes_erat(n):
  return list(itertools.takewhile(lambda p: p<n, erat2()))

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.