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
I don't think you'll find an algorithm for checking an arbitrary number for primality with an O(n) time complexity. I'm pretty certain the NSA (and any other organisations that deal with crypto issues) wouldn't be very happy with that :-)
The only way you'll get an O(n) or better way is to pre-calculate (for example) the first fifty million primes (or use someone else's already-precalculated list) and use that as a lookup. I have such a file locally and it's a simple matter of running grep
over it to see if the number is prime. It doesn't help for arbitrary numbers but I rarely have to use ones that big. Crypto guys, of course, would consider such a list vanishingly small for their purposes.
And, if you turn it into a bitmap (about 120M for the first fifty million primes), you can even even reduce the complexity to O(1) by simply turning the number into a byte offset and bit mask - a couple of bit shifts and/or bitwise operations.
However, getting a list of the primes below a certain n
is certainly doable in O(n) time complexity. The Atkin and Bernstein paper detailing the Sieve of Atkin claims:
We introduce an algorithm that computes the prime numbers up to N using
O(N/log(log(N)))
additions ...
which is actually slightly better than O(n).
However, it's still unlikely to compete with a lookup solution. My advice would be to use Atkin or Eratosthenes to make a list - it doesn't really matter since you'll only be doing this bit once so performance would not be critical.
Then use the list itself for checking primality.
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.