<code>unionAll</code> can be defined as an ever-growing, right-deepening unbounded [[#Tree_merging|tree of comparisons]] like the <code>joinT</code> function below, or it can use a (fixed-sized) array as a segment-wise sorting and duplicates-removing device, to join together the streams of multiples of primes. The processing is naturally divided up into segments between the successive squares of primes.

+

<code>unionAll</code> can be defined as an ever-growing, right-deepening unbounded [[#Tree_merging|tree of comparisons]] like the <code>joinT</code> function below, or it can use a (fixed-sized) array as a segment-wise sorting and duplicates-removing device, to join together the streams of multiples of primes. The processing naturally divides up into segments between the successive squares of primes.

Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]).

Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]).

Line 186:

Line 186:

But segmentation doesn't add anything substantially, and each multiples stream starts at its prime's square anyway. What does the [[#Postponed|Postponed]] code do, operationally? For each prime's square passed over, it builds up a nested linear ''left-deepening'' structure, '''''(...((xs-a)-b)-...)''''', where '''''xs''''' is the original odds-producing ''[3,5..]'' list, so that each odd it produces must go through more and more <code>`minus`</code> nodes on its way up - and those odd numbers that eventually emerge on top are prime. Thinking a bit about it, wouldn't another, ''right-deepening'' structure, '''''(xs-(a+(b+...)))''''', be better? This idea is due to Richard Bird (in the code presented in Melissa O'Neill's article).

But segmentation doesn't add anything substantially, and each multiples stream starts at its prime's square anyway. What does the [[#Postponed|Postponed]] code do, operationally? For each prime's square passed over, it builds up a nested linear ''left-deepening'' structure, '''''(...((xs-a)-b)-...)''''', where '''''xs''''' is the original odds-producing ''[3,5..]'' list, so that each odd it produces must go through more and more <code>`minus`</code> nodes on its way up - and those odd numbers that eventually emerge on top are prime. Thinking a bit about it, wouldn't another, ''right-deepening'' structure, '''''(xs-(a+(b+...)))''''', be better? This idea is due to Richard Bird (in the code presented in Melissa O'Neill's article).

−

Here, ''xs'' would stay near the top, and ''more frequently'' odds-producing streams of multiples of ''smaller'' primes would be above those of the ''bigger'' primes, that produce ''less frequently'' their candidates which have to pass through ''more'' <code>`union`</code> nodes on their way up. Plus, no explicit synchronization is necessary anymore because the produced multiples of a prime start at its square anyway - just some care has to be taken to avoid a runaway access to the infinitely-defined structure (specifically, if each <code>(+)</code> operation passes along unconditionally its left child's head value ''before'' polling the right child's head value, then we are safe).

Here, ''xs'' stays near the top, and ''more frequently'' odds-producing streams of multiples of ''smaller'' primes are above those of the ''bigger'' primes, that produce ''less frequently'' their candidates which have to pass through ''more'' <code>`union`</code> nodes on their way up. Plus, no explicit synchronization is necessary anymore because the produced multiples of a prime start at its square anyway - just some care has to be taken to avoid a runaway access to the indefinitely-defined structure (specifically, if each <code>(+)/union</code> operation passes along unconditionally its left child's head value ''before'' polling the right child's head value, then we are safe).

−

Here's the code, faster yet but still with same time complexity of about <math>O(n^{1.4})</math>:

+

To prevent unneeded memoization and thus prevent a memory leak, double primes feed can be introduced as per Melissa O'Neill's code. Here's the code, faster yet but still with the same empirical orders of growth of about ~ <math> n^{1.4}</math>:

This allows the <code>primesLME</code> stream to be discarded immediately as it is being consumed by its consumer. With <code>primes'</code> it is impossible, as each produced member of <code>primes'</code> is needed later as input to the same <code>primes'</code> stream definition. So the <code>primes'</code> stream feeds in a loop to itself, and thus is retained in memory; and it is also used as input stream for the main stream production, but it reaches only up to a square root of where the main stream, <code>primesLME</code>, reaches, as its production is demanded by its consumer(s).

=== Tree merging ===

=== Tree merging ===

Line 279:

Line 286:

<haskell>

<haskell>

primesFrom m = filter isPrime [m..]

primesFrom m = filter isPrime [m..]

+

</haskell>

+

+

=== Map-based ===

+

Runs ~1.7x slower than [[#Tree_merging|TME version]], but with the same empirical time complexity, ~<math>n^{1.2}</math> (in ''n'' primes produced) and same very low (near constant) memory consumption:

This code is extremely inefficient, running above <math>O({n^{2}})</math> complexity (and worsening rapidly), and should be regarded a ''specification'' only. Its memory usage is very high, with space complexity just below <math>O({n^{2}})</math>, in ''n'' primes produced.

+

This code is extremely inefficient, running above <math>O({n^{2}})</math> empirical complexity (and worsening rapidly), and should be regarded a ''specification'' only. Its memory usage is very high, with empirical space complexity just below <math>O({n^{2}})</math>, in ''n'' primes produced.

+

+

In the stream-based sieve of Eratosthenes we are able to ''skip'' along the input stream <code>xs</code> directly to the prime's square, consuming the whole prefix at once, thus achieving the results equivalent to the postponement technique, because the generation of the prime's multiples is independent of the rest of the stream.

+

+

But here in the Euler's sieve it ''is'' dependent on all <code>xs</code> and we're unable ''in principle'' to skip along it to the prime's square - because all <code>xs</code> are needed for each prime's multiples generation. Thus efficient unbounded stream-based implementation seems to be impossible, in principle.

=== Wheeled list representation ===

=== Wheeled list representation ===

Revision as of 22:45, 30 December 2012

In mathematics, amongst the natural numbers greater than 1, a prime number (or a prime) is such that has no divisors other than itself (and 1).

O'Neill, Melissa E., "The Genuine Sieve of Eratosthenes", Journal of Functional Programming, Published online by Cambridge University Press 9 October 2008 doi:10.1017/S0956796808007004.

2 Definition

In mathematics, amongst the natural numbers greater than 1, a prime number (or a prime) is such that has no divisors other than itself (and 1). The smallest prime is thus 2. Non-prime numbers are known as composite, i.e. those representable as product of two natural numbers greater than 1. The set of prime numbers is thus

Thus starting with 2, for each newly found prime we can eliminate from the rest of the numbers all the multiples of this prime, giving us the next available number as next prime. This is known as sieving the natural numbers, so that in the end all the composites are eliminated and what we are left with are just primes. (This is what the last formula is describing, though seemingly impredicative, because it is self-referential. But because N2 is well-ordered (with the order being preserved under addition), the formula is well-defined.)

To eliminate a prime's multiples we can either a. test each new candidate number for divisibility by that prime, giving rise to a kind of trial division algorithm; or b. we can directly generate the multiples of a prime p by counting up from it in increments of p, resulting in a variant of the sieve of Eratosthenes.

Having a direct-access mutable arrays indeed enables easy marking off of these multiples on pre-allocated array as it is usually done in imperative languages; but to get an efficient list-based code we have to be smart about combining those streams of multiples of each prime - which gives us also the memory efficiency in generating the results incrementally, one by one.

3 Sieve of Eratosthenes

The sieve of Eratosthenes calculates primes as natural numbers above 1 without the composites, where composites are found as sequences of multiples of each prime, generated by counting up from the prime's square in constant increments equal to that prime (or twice that much, for odd primes):

unionAll can be defined as an ever-growing, right-deepening unbounded tree of comparisons like the joinT function below, or it can use a (fixed-sized) array as a segment-wise sorting and duplicates-removing device, to join together the streams of multiples of primes. The processing naturally divides up into segments between the successive squares of primes.

This should be regarded more like a specification, not a code. It is extremely slow, running at empirical time complexities worse than quadratic in number of primes produced. But it has the core defining features of the classical formulation of S. of E. as a. being bounded, i.e. having a top limit value, and b. finding out the multiples of a prime directly, by counting up from it in increments equal to that prime (or twice that, for odd primes).

The name merge ought to be reserved for duplicates-preserving merging operation of mergesort.

3.2 Analysis

So for each newly found prime the sieve removes its odd multiples from further consideration. It finds them by counting up in steps of 2p. There are thus O(m / p) multiples generated and eliminated for each prime, and O(mloglog(m)) multiples in total, with duplicates, by virtues of prime harmonic series.

If each multiple is dealt with in O(1) time, this will translate into O(mloglog(m)) RAM machine operations (since we consider addition as an atomic operation). Indeed mutable random-access arrays allow for that. But lists in Haskell are sequential-access, and complexity of minus(a,b) for lists is instead of of the direct access destructive array update. The lower the complexity of each minus step, the better the overall complexity.

So on k-th step the argument list (p:xs) that the eratos function gets starts with the (k+1)-th prime, and consists of all the numbers ≤ m coprime with all the primes ≤ p. According to the M. O'Neill's article (p.10) there are such numbers.

It looks like for our intents and purposes. Since the number of primes below m is n = π(m) = O(m / log(m)) by the prime number theorem (where π(m) is a prime counting function), there will be n multiples-removing steps in the algorithm; it means total complexity of at least O(mn / log(n)) = O(m2 / (log(m))2), or O(n2) in n primes produced - much much worse than the optimal O(nlog(n)loglog(n)).

3.3 From Squares

But we can start each step at a prime's square, as its smaller multiples will have been already produced on previous steps. This means we can stop early, when the prime's square reaches the top value m, and thus cut the total number of steps to around . This does not in fact change the complexity of random-access code, but for lists it makes it O(m1.5 / (logm)2), or O(n1.5 / (logn)0.5) in n primes produced, a dramatic speedup:

Its empirical complexity is about O(n1.45). This simple optimization works here because our formulation is bounded, as is the original algorithm. To start late on a bounded sequence is to stop early (if we start past its end we don't need to start at all – see warning below), thus preventing the creation of all the superfluous multiples streams which started above the upper bound anyway. This is acceptably slow now, striking a good balance between clarity, succinctness and efficiency.

Warning: this is predicated on a subtle point of minus xs [] = xs definition being used, as it indeed should be. If the definition minus (x:xs) [] = x:minus xs [] is used, the problem is back and the complexity is bad again.

3.4 Guarded

This ought to be explicated (improving on clarity, though not on time complexity) as in the following, for which it is indeed a minor optimization whether to start from p or p*p - because it explicitly stops as soon as possible:

It is now clear that it can't be made unbounded just by abolishing the upper bound m, because the guard can not be simply omitted without changing the complexity back for the worst.

3.5 Accumulating Array

So while minus(a,b) takes O( | b | ) operations for random-access imperative arrays and about O( | a | ) operations for lists here, using Haskell's immutable array for a one could expect the array update time to be nevertheless closer to O( | b | ) if destructive update were used implicitly by compiler for an array being passed along as an accumulating parameter:

This indeed seems to be working for unboxed arrays, with the type signature added explicitly (suggested by Daniel Fischer), the above code running relatively very fast, with empirical complexity of about O(n1.15..1.45) in n primes produced (for producing from few hundred thousands to few millions primes, memory usage also slowly growing). But it relies on specific compiler optimizations, and indeed if we remove the explicit type signature, the code above turns very slow.

How can we write code that we'd be certain about? One way is to use explicitly mutable monadic arrays (see below), but we can also think about it a little bit more on the functional side of things still.

3.6 Postponed

Going back to guarded Eratosthenes, first we notice that though it works with minimal number of prime multiples streams, it still starts working with each a bit prematurely. Fixing this with explicit synchronization won't change complexity but will speed it up some more:

Since the removal of a prime's multiples here starts at the right moment, and not just from the right place, the code could now finally be made unbounded. Because no multiples-removal process is started prematurely, there are no extraneous multiples streams, which were the reason for the extreme wastefulness and thus inefficiency of the original formulation.

3.7 Segmented

With work done segment-wise between the successive squares of primes it becomes

This "marks" the odd composites in a given range by generating them - just as a person performing the original sieve of Eratosthenes would do, counting one by one the multiples of the relevant primes. These composites are independently generated so some will be generated multiple times.

The advantage to working in spans explicitly is that this code is easily amendable to using arrays for the composites marking and removal on each finite span; and memory usage can be kept in check by using fixed sized segments.

3.7.1 Segmented Tree-merging

Rearranging the chain of subtractions into a subtraction of merged streams (see below) and using tree-like folding structure, further speeds up the code and significantly improves its asymptotic time behavior (down to about O(n1.28empirically), space is leaking though):

3.8 Linear merging

But segmentation doesn't add anything substantially, and each multiples stream starts at its prime's square anyway. What does the Postponed code do, operationally? For each prime's square passed over, it builds up a nested linear left-deepening structure, (...((xs-a)-b)-...), where xs is the original odds-producing [3,5..] list, so that each odd it produces must go through more and more `minus` nodes on its way up - and those odd numbers that eventually emerge on top are prime. Thinking a bit about it, wouldn't another, right-deepening structure, (xs-(a+(b+...))), be better? This idea is due to Richard Bird (in the code presented in Melissa O'Neill's article).

Here, xs stays near the top, and more frequently odds-producing streams of multiples of smaller primes are above those of the bigger primes, that produce less frequently their candidates which have to pass through more`union` nodes on their way up. Plus, no explicit synchronization is necessary anymore because the produced multiples of a prime start at its square anyway - just some care has to be taken to avoid a runaway access to the indefinitely-defined structure (specifically, if each (+)/union operation passes along unconditionally its left child's head value before polling the right child's head value, then we are safe).

To prevent unneeded memoization and thus prevent a memory leak, double primes feed can be introduced as per Melissa O'Neill's code. Here's the code, faster yet but still with the same empirical orders of growth of about ~ n1.4:

This allows the primesLME stream to be discarded immediately as it is being consumed by its consumer. With primes' it is impossible, as each produced member of primes' is needed later as input to the same primes' stream definition. So the primes' stream feeds in a loop to itself, and thus is retained in memory; and it is also used as input stream for the main stream production, but it reaches only up to a square root of where the main stream, primesLME, reaches, as its production is demanded by its consumer(s).

3.9 Tree merging

Moreover, it can be changed into a tree structure. This idea is due to Dave Bayer on haskell-cafe mailing list (though in much more complex formulation):

3.10 Tree merging with Wheel

Wheel factorization optimization can be further applied, and another tree structure can be used which is better adjusted for the primes multiples production (effecting about 5%-10% at the top of a total 2.5x speedup w.r.t. the above tree merging on odds only - though complexity stays roughly the same):

4 Turner's sieve - Trial division

David Turner's original 1975 formulation (SASL Language Manual, 1975) replaces non-standard `minus` in the sieve of Eratosthenes by stock list comprehension with rem filtering, turning it into a kind of trial division algorithm:

This creates an immense number of superfluous implicit filters in extremely premature fashion. To be admitted as prime, each number will be tested for divisibility here by all its preceding primes potentially, while just those not greater than its square root would suffice. To find e.g. the 1001st prime (7927), 1000 filters are used, when in fact just the first 24 are needed (up to 89's filter only). Operational overhead is enormous here.

4.1 Guarded Filters

But this really ought to be changed into bounded and guarded variant, again achieving the "miraculous" complexity improvement from above quadratic to about O(n1.45) empirically (in n primes produced):

creating here as well the linear nested structure at run-time, (...(([3,5..] >>= filterBy [3]) >>= filterBy [5])...), where filterBy ds n = [n | noDivs ds n] (see noDivs definition below) – but unlike the original code, each filter being created at its proper moment, not sooner than the prime's square is seen.

4.3 Optimal trial division

The above is equivalent to the traditional formulation of trial division,

except that this code is rechecking for each candidate number which primes to use, whereas for every candidate number in each segment between the successive squares of primes these will just be the same prefix of the primes list being built.

4.4 Segmented Generate and Test

This primes prefix's length can be explicitly maintained, achieving a certain further speedup (though not in complexity which stays the same) by turning a list of filters into one filter by an explicit list of primes:

4.5 Conclusions

All these variants of course being variations of trial division – finding out primes by direct divisibility testing of every odd number by sequential primes below its square root (instead of just by its factors, which is what direct generation of multiples is doing, essentially) – are thus of principally worse complexities than that of Sieve of Eratosthenes.

The prototype code is very inefficient, yet improving significantly with just a simple use of bounded, guarded formulation. So, there's no harm in applying simple improvements to a code instead of just labeling it "naive". BTW were divisibility testing somehow turned into an O(1) operation, e.g. by some kind of massive parallelization, the overall complexity of trial division sieve would drop to O(n). It's the sequentiality of testing that's the culprit.

Did Eratosthenes himself achieve the optimal complexity? It rather seems doubtful, as he probably counted boxes in the table by 1 to go from one number to the next, as in 3,5,7,9,11,13,15, ... for he had no access even to Hindu numerals, using Greek alphabet for writing down numbers instead. Was he performing a genuine sieve of Eratosthenes then? Should faithfulness of an algorithm's implementation be judged by its performance?

So the initial Turner code is just a one-liner that ought to have been regarded as executable specification in the first place. The reason it was taught that way is probably so that it could provoke discussion among students, at the very least discovering the optimization technique of the postponement of filter-creation.

5 Euler's Sieve

5.1 Unbounded Euler's sieve

With each found prime Euler's sieve removes all its multiples in advance so that at each step the list to process is guaranteed to have no multiples of any of the preceding primes in it (consists only of numbers coprime with all the preceding primes) and thus starts with the next prime:

This code is extremely inefficient, running above O(n2) empirical complexity (and worsening rapidly), and should be regarded a specification only. Its memory usage is very high, with empirical space complexity just below O(n2), in n primes produced.

In the stream-based sieve of Eratosthenes we are able to skip along the input stream xs directly to the prime's square, consuming the whole prefix at once, thus achieving the results equivalent to the postponement technique, because the generation of the prime's multiples is independent of the rest of the stream.

But here in the Euler's sieve it is dependent on all xs and we're unable in principle to skip along it to the prime's square - because all xs are needed for each prime's multiples generation. Thus efficient unbounded stream-based implementation seems to be impossible, in principle.

5.2 Wheeled list representation

The situation can be somewhat improved using a different list representation, for generating lists not from a last element and an increment, but rather a last span and an increment, which entails a set of helpful equivalences:

Generating a list from a span specification is like rolling a wheel as its pattern gets repeated over and over again. For each span specification w@((p:_),_) produced by eulerStep, the numbers in (fromSpan w) up to p2 are all primes too, so that

This runs at about O(n1.5..1.8) complexity, for n primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).

6 Using Immutable Arrays

6.1 Generating Segments of Primes

The sieve of Eratosthenes'es removal of multiples on each segment of odds can be done by actually marking them in an array instead of manipulating the ordered lists, and can be further sped up more than twice by working with odds only, represented as their offsets in segment arrays:

Run on Ideone.com it is somewhat faster than Tree Merging With Wheel in producing first million primes or two, but has worse time complexity and large memory footprint which quickly gets into hundreds of MBs.

When the (commented out above) explicit type signature is added, making the same code work on unboxed arrays, the resulting GHC-compiled code runs more than twice faster and with better empirical complexity, of about O(n1.10..1.05) in producing first few millions of primes, with smaller though still growing memory footprint. Fixed sized segments are usually used in segmented sieves to limit the memory usage.

Although using odds instead of primes, the array generation is so fast that it is very much feasible and even preferable for quick generation of some short spans of relatively big primes.

7 Using Mutable Arrays

Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.

7.1 Using ST Array

This method implements the Sieve of Eratosthenes, similar to how you might do it
in C, modified to work on odds only. It is fast, but about linear in memory consumption, allocating one (though apparently packed) sieve array for the whole sequence to process.

Its empirical time complexity is improving with n (number of primes produced) from above O(n1.20) towards O(n1.16). The reference C++ vector-based implementation exhibits this improvement in empirical time complexity too, from O(n1.5) gradually towards O(n1.12), where tested (which might be interpreted as evidence towards the expected quasilinearithmicO(nlog(n)log(logn)) time complexity).

7.2 Bitwise prime sieve with Template Haskell

Count the number of prime below a given 'n'. Shows fast bitwise arrays,
and an example of Template Haskell to defeat your enemies.

11 Testing Primality, and Integer Factorization

12 One-liners

13 External links

A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill.

WARNING: Don't use the priority queue from older versions of that file for your projects: it's broken and works for primes only by a lucky chance. The revised version of the file fixes the bug, as pointed out by Eugene Kirpichov on February 24, 2009 on the haskell-cafe mailing list, and fixed by Bertram Felgenhauer.