Suppose I've got a natural number n
and I want a list (or whatever) of all primes up to n
.
The classic prime sieve algorithm runs in O(n log n)
time and O(n)
space -- it's fine for more imperative languages, but requires in-place modification to lists and random access, in a fundamental way.
There's a functional version involving priority queues, which is pretty slick -- you can check it out here. This has better space complexity at about O(n / log(n))
(asymptotically better but debatable at practical scales). Unfortunately the time analysis is nasty, but it's very nearly O(n^2)
(actually, I think it's about O(n log(n) Li(n))
, but log(n) Li(n)
is approximately n
).
Asymptotically speaking it would actually be better just to check the primality of each number as you generate it, using successive trial division, as that would take only O(1)
space and O(n^{3/2})
time. Is there a better way?
Edit: it turns out my calculations were simply incorrect. The algorithm in the article is O(n (log n) (log log n))
, which the articles explains and proves (and see the answer below), not the complicated mess I put above. I'd still enjoy seeing a bona-fide O(n log log n)
pure algorithm if there is one out there.