[Python] Sieve of Eratosthenes - Finding Primes Python

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    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 primes

    print 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 = 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==True]

    print primes_sieve1(2000000)

    Continue reading...

Compartilhe esta Página