Python- Sieve of Eratosthenes- Compact Python

后端 未结 8 1315
醉话见心
醉话见心 2021-01-06 14:09

This is my code for finding primes using the Sieve of Eratosthenes.

list = [i for i in range(2, int(raw_input(\"Compute primes up to what number? \"))+1)]  
         


        
8条回答
  •  悲哀的现实
    2021-01-06 14:21

    You are not doing the Sieve of Eratosthenes; the danger of not properly implementing the algorithm is that it will be extremely slow. Try your algorithm on 10**6 for example.

    Shortest implementation of the bounded Sieve of Eratosthenes I can come up with:

    def primes(upTo):
        isPrime = list(range(upTo))
        for p in range(2,int(upTo**0.5)+1): #p: 2,3,4,...,sqrt(N)
            print(p, isPrime[p])
            if isPrime[p]:
                for multiple in range(p**2,upTo,p): #mult: p^2, p^2+p, p^2+2p, ..., N
                    isPrime[multiple] = False
        return [x for x in isPrime[2:] if x]
    

    Demo:

    >>> list(primes(29))
    [2, 3, 5, 7, 11, 13, 17, 19, 23]
    

    It's actually rather succinct, if you ignore linebreaks and the massive skip-even-numbers optimization:

    isPrime=[True]*upTo for p in range(2,upTo): if isPrime[p]: yield p for m in range(p,upTo,p): isPrime[m]=False
    

提交回复
热议问题