reporting all prime numbers less than n

前端 未结 2 1714
暖寄归人
暖寄归人 2021-01-16 20:06

I need to print all the prime numbers less than a given number n. I can use sieve of Eratothenes but the running time of that algorithm IS NOT O(n). Is there any O(n) time s

2条回答
  •  一整个雨季
    2021-01-16 20:32

    The Sieve of Eratosthenes has time complexity O(n log log n). The function log log n grows very slowly; for example, log(log(10^9)) = 3. That means you can effectively treat the log log n part of the time complexity as a constant, and ignore it, giving a time complexity of "nearly" O(n).

    There are various algorithms that operate in time O(n) or O(n / log log n), including Pritchard's wheel sieves and Atkins' sieve. But constant factors generally make those algorithms slower in practice than the Sieve of Eratosthenes. Unless you need extreme speed, and you know what you are doing, and you are willing to spend lots of time doing it, the practical answer is the Sieve of Eratosthenes.

    Your question says that you are going to print the list of primes. In that case, output will dominate the run time of any algorithm you choose. So do yourself a favor and implement a simple Sieve of Eratosthenes.

提交回复
热议问题