A Fast Prime Number Sieve in Python

前端 未结 2 1297
忘了有多久
忘了有多久 2020-12-06 13:16

I have been going through prime number generation in python using the sieve of Eratosthenes and the solutions which people tout as a relatively fast option such as those in

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 14:04

    I transformed your code to fit into the prime sieve comparison script of @unutbu at Fastest way to list all primes below N as follows:

    def sieve_for_primes_to(n):
        size = n//2
        sieve = [1]*size
        limit = int(n**0.5)
        for i in range(1,limit):
            if sieve[i]:
                val = 2*i+1
                tmp = ((size-1) - i)//val 
                sieve[i+val::val] = [0]*tmp
        return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]
    

    On my MBPro i7 the script is fast calculating all primes < 1000000 but actually 1.5 times slower than rwh_primes2, rwh_primes1 (1.2), rwh_primes (1.19) and primeSieveSeq (1.12) (@andreasbriese at the page end).

提交回复
热议问题