Quantcast
Viewing all articles
Browse latest Browse all 28

Sieve of Eratosthenes - Finding Primes Python

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

I have written an implementation of it in Python. But it's terribly slow. For say, if I want to find all primes less than 2 million. It takes > 20 mins. (I stopped it at this point). How can I speed this up?

def primes_sieve(limit):    limitn = limit+1    primes = range(2, limitn)    for i in primes:        factors = range(i, limitn, i)        for f in factors[1:]:            if f in primes:                primes.remove(f)    return primesprint primes_sieve(2000)

UPDATE:I ended up doing profiling on this code & found that quite a lot of time was spent on removing an element from the list. Quite understandable considering it has to traverse the entire list (worst-case) to find the element & then remove it and then readjust the list (maybe some copy goes on?). Anyway, I chucked out list for dictionary. My new implementation -

def primes_sieve1(limit):    limitn = limit+1    primes = dict()    for i in range(2, limitn): primes[i] = True    for i in primes:        factors = range(i,limitn, i)        for f in factors[1:]:            primes[f] = False    return [i for i in primes if primes[i]==True]print primes_sieve1(2000000)

Viewing all articles
Browse latest Browse all 28

Trending Articles



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