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

后端 未结 7 2014
遇见更好的自我
遇见更好的自我 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:14

    In the naive method, you do O(sqrt(num)) operations for each number num you check for primality. Ths is O(n*sqrt(n)) total.

    In the sieve method, for each unmarked number from 1 to n you do n / 2 operations when marking multiples of 2, n / 3 when marking those of 3, n / 5 when marking those of 5 etc. This is n*(1/2 + 1/3 + 1/5 + 1/7 + ...), which is O(n log log n). See here for that result.

    So the asymptotic complexity is not the same, like you said. Even a naive sieve will beat the naive prime-generation method pretty fast. Optimized versions of the sieve can get much faster, but the big-oh remains unchanged.

    The two are not equivalent like you say. For each number, you will check divisibility by the same primes 2, 3, 5, 7, ... in the naive prime-generation algorithm. As you progress, you check divisibility by the same series of numbers (and you keep checking against more and more as you approach your n). For the sieve, you keep checking less and less as you approach n. First you check in increments of 2, then of 3, then 5 and so on. This will hit n and stop much faster.

提交回复
热议问题