Quantcast
Channel: Sieve of Eratosthenes - Finding Primes Python - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by Glenn Maynard for Sieve of Eratosthenes - Finding Primes Python

$
0
0

Removing from the beginning of an array (list) requires moving all of the items after it down. That means that removing every element from a list in this way starting from the front is an O(n^2) operation.

You can do this much more efficiently with sets:

def primes_sieve(limit):    limitn = limit+1    not_prime = set()    primes = []    for i in range(2, limitn):        if i in not_prime:            continue        for f in range(i*2, limitn, i):            not_prime.add(f)        primes.append(i)    return primesprint primes_sieve(1000000)

... or alternatively, avoid having to rearrange the list:

def primes_sieve(limit):    limitn = limit+1    not_prime = [False] * limitn    primes = []    for i in range(2, limitn):        if not_prime[i]:            continue        for f in xrange(i*2, limitn, i):            not_prime[f] = True        primes.append(i)    return primes

Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>