python prime numbers Sieve of Eratosthenes

前端 未结 6 1007
旧时难觅i
旧时难觅i 2020-12-28 11:15

Hi can anyone tell me how to implement Sieve of Eratosthenes within this code to make it fast? Help will be really appreciated if you can complete it with sieve. I am really

6条回答
  •  心在旅途
    2020-12-28 11:50

    Both the original poster and the other solution posted here make the same mistake; if you use the modulo operator, or division in any form, your algorithm is trial division, not the Sieve of Eratosthenes, and will be far slower, O(n^2) instead of O(n log log n). Here is a simple Sieve of Eratosthenes in Python:

    def primes(n): # sieve of eratosthenes
        ps, sieve = [], [True] * (n + 1)
        for p in range(2, n + 1):
            if sieve[p]:
               ps.append(p)
               for i in range(p * p, n + 1, p):
                   sieve[i] = False
        return ps
    

    That should find all the primes less than a million in less than a second. If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.

提交回复
热议问题