Why is Sieve of Eratosthenes more efficient than the simple “dumb” algorithm?

后端 未结 7 2002
遇见更好的自我
遇见更好的自我 2020-12-08 21:56

If you need to generate primes from 1 to N, the \"dumb\" way to do it would be to iterate through all the numbers from 2 to N and check if the numbers are divisable by any p

相关标签:
7条回答
  • 2020-12-08 22:36

    Because with the sieve method, you stop marking mutiples of the running primes when the running prime reaches the square root of N.

    Say, you want to find all primes less than a million.

    First you set an array

    for i = 2 to 1000000
      primetest[i] = true
    

    Then you iterate

    for j=2 to 1000         <--- 1000 is the square root of 10000000
      if primetest[j]                                    <--- if j is prime
        ---mark all multiples of j (except j itself) as "not a prime"
        for k = j^2 to 1000000 step j
          primetest[k] = false
    

    You don't have to check j after 1000, because j*j will be more than a million. And you start from j*j (you don't have to mark multiples of j less than j^2 because they are already marked as multiples of previously found, smaller primes)

    So, in the end you have done the loop 1000 times and the if part only for those j's that are primes.

    Second reason is that with the sieve, you only do multiplication, not division. If you do it cleverly, you only do addition, not even multiplication.

    And division has larger complexity than addition. The usual way to do division has O(n^2) complexity, while addition has O(n).

    0 讨论(0)
提交回复
热议问题