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

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

    A "naive" Sieve of Eratosthenes will mark non-prime numbers multiple times. But, if you have your numbers on a linked list and remove numbers taht are multiples (you will still need to walk the remainder of the list), the work left to do after finding a prime is always smaller than it was before finding the prime.

提交回复
热议问题