Difference between revisions of "Prime numbers"

From HaskellWiki
Jump to navigation Jump to search
(→‎Segmented: adding tree-merging segmented code variant here instead of forcing user chase links into external site)
(153 intermediate revisions by 2 users not shown)
Line 1: Line 1:
In mathematics, a ''prime number'' (or a ''prime'') is a natural number which has exactly two distinct natural number divisors: 1 and itself. The smallest prime is thus 2.
+
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).
 
Any natural number is representable as a product of powers of its prime factors, and so a prime has no prime divisors other than itself. That means that starting with 2, ''for each'' newly found ''prime'' we can ''eliminate'' from the rest of the numbers ''all such numbers'' that have this prime as their divisor, giving us the ''next available'' number as next prime. This is known as ''sieving'' the natural numbers, so that in the end what we are left with are just primes.
 
 
To eliminate a prime's multiples from the result we can either '''a.''' plainly test each new candidate number for divisibility by that prime with a direct test, giving rise to a kind of ''"trial division"'' algorithm; or '''b.''' we can find out multiples of a prime ''<code>p</code>'' by ''counting up'' from it by ''<code>p</code>'' numbers at a time, resulting in a variant of a ''"genuine sieve"'' as it was reportedly originally conceived by Eratosthenes in ancient Greece.
 
 
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 one by one.
 
   
 
== Prime Number Resources ==
 
== Prime Number Resources ==
Line 14: Line 8:
   
 
* HackageDB packages:
 
* HackageDB packages:
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorisation ...
+
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...
 
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.
 
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.
 
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.
 
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.
Line 21: Line 15:
 
* Papers:
 
* Papers:
 
** O'Neill, Melissa E., [http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf "The Genuine Sieve of Eratosthenes"], Journal of Functional Programming, Published online by Cambridge University Press 9 October 2008 doi:10.1017/S0956796808007004.
 
** O'Neill, Melissa E., [http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf "The Genuine Sieve of Eratosthenes"], Journal of Functional Programming, Published online by Cambridge University Press 9 October 2008 doi:10.1017/S0956796808007004.
  +
  +
== 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
  +
  +
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}
  +
  +
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}
  +
  +
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>}
  +
  +
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }
  +
  +
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }
  +
  +
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' }
  +
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}
  +
  +
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. <small>(This is what the last formula is describing, though seemingly [http://en.wikipedia.org/wiki/Impredicativity impredicative], because it is self-referential. But because '''N'''<sub>2</sub> is well-ordered (with the order being preserved under addition), the formula is well-defined.)</small>
  +
  +
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 ''<code>p</code>'' by counting up from it in increments of ''<code>p</code>'', 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 [[#Tree merging with Wheel|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.
   
 
== Sieve of Eratosthenes ==
 
== Sieve of Eratosthenes ==
  +
Sieve of Eratosthenes is ''genuinely'' represented by
 
  +
The sieve of Eratosthenes calculates primes as ''integers above 1 that are not multiples of primes'', i.e. ''not composite'' &mdash; whereas composites are found as a union of 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):
  +
 
<haskell>
 
<haskell>
  +
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])
-- genuine yet wasteful sieve of Eratosthenes
 
  +
primesTo m = 2 : eratos [3,5..m] where
 
  +
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy
eratos [] = []
 
eratos (p:xs) = p : eratos (xs `minus` [p,p+2*p..m])
+
-- under n (minus a b) == under n a \\ under n b
-- eulers (p:xs) = p : eulers (xs `minus` map (p*)(p:xs))
+
-- under n (union a b) == nub . sort $ under n a ++ under n b
-- turner (p:xs) = p : turner [x | x<-xs, rem x p /= 0]
+
-- under n . _U == nub . sort . concat . map (under n)
 
</haskell>
 
</haskell>
   
  +
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.
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 S. of E. as '''''a.''''' being bounded, i.e. having a top limit value, and '''''b.''''' finding out the multiples of a prime by counting up from it. Yes, this is exactly how Eratosthenes defined it ([http://www.archive.org/stream/nicomachigerasen00nicouoft#page/29/mode/1up Nicomachus, ''Introduction to Arithmetic'', I, pp. 13, 31]).
 
   
  +
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use an <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.
The canonical list-difference <code>minus</code> and duplicates-removing list-union <code>union</code> functions dealing with ordered increasing lists - infinite as well as finite - are simple enough to define (using <code>compare</code> has an effect of comparing the values only once, unlike when using (<) etc):
 
  +
  +
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]).
  +
  +
=== Initial definition ===
  +
  +
To start with, the sieve of Eratosthenes can be genuinely represented by
  +
<haskell>
  +
-- genuine yet wasteful sieve of Eratosthenes
  +
primesTo m = eratos [2..m] where
  +
eratos [] = []
  +
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])
  +
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])
  +
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))
  +
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0]
  +
</haskell>
  +
  +
This should be regarded more like a ''specification'', not a code. It runs at [https://en.wikipedia.org/wiki/Analysis_of_algorithms#Empirical_orders_of_growth empirical orders of growth] 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 constant increments, equal to that prime.
  +
  +
The canonical list-difference <code>minus</code> and duplicates-removing <code>union</code> functions dealing with ordered increasing lists (cf. [http://hackage.haskell.org/packages/archive/data-ordlist/latest/doc/html/Data-List-Ordered.html Data.List.Ordered package]) are:
 
<haskell>
 
<haskell>
-- ordered lists, difference and union
+
-- ordered lists, difference and union
minus (x:xs) (y:ys) = case (compare x y) of
+
minus (x:xs) (y:ys) = case (compare x y) of
 
LT -> x : minus xs (y:ys)
 
LT -> x : minus xs (y:ys)
 
EQ -> minus xs ys
 
EQ -> minus xs ys
 
GT -> minus (x:xs) ys
 
GT -> minus (x:xs) ys
minus xs _ = xs
+
minus xs _ = xs
union (x:xs) (y:ys) = case (compare x y) of
+
union (x:xs) (y:ys) = case (compare x y) of
 
LT -> x : union xs (y:ys)
 
LT -> x : union xs (y:ys)
 
EQ -> x : union xs ys
 
EQ -> x : union xs ys
 
GT -> y : union (x:xs) ys
 
GT -> y : union (x:xs) ys
union xs ys = xs ++ ys
+
union xs [] = xs
  +
union [] ys = ys
 
</haskell>
 
</haskell>
   
(the name ''merge'' ought to be reserved for duplicates-preserving merging as used by ''mergesort'' - that's why we use ''union'' here, following Leon P.Smith's [http://hackage.haskell.org/packages/archive/data-ordlist/0.4.4/doc/html/Data-List-Ordered.html Data.List.Ordered] package).
+
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.
   
 
=== Analysis ===
 
=== Analysis ===
   
So what does it do, this sieve code? For each found prime it removes its ''odd'' multiples from further consideration. It finds them by counting up in steps of ''2p''. There are thus '''<math>O(m/p)</math>''' multiples for each prime, and '''<math>O(m \log\log(m))</math>''' multiples total, with duplicates, by virtues of ''prime harmonic series'', where <math>\sum_{p_i<m}{1/p_i} = O(\log\log(m))</math>.
+
So for each newly found prime the sieve discards its multiples, enumerating them by counting up in steps of ''p''. There are thus <math>O(m/p)</math> multiples generated and eliminated for each prime, and <math>O(m \log \log(m))</math> multiples in total, with duplicates, by virtues of [http://en.wikipedia.org/wiki/Prime_harmonic_series prime harmonic series].
  +
  +
If each multiple is dealt with in <math>O(1)</math> time, this will translate into <math>O(m \log \log(m))</math> 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 <code>minus(a,b)</code> for lists is <math>\textstyle O(|a \cup b|)</math> instead of <math>\textstyle O(|b|)</math> 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 <code>(p:xs)</code> that the <code>eratos</code> function gets starts with the ''(k+1)''-th prime, and consists of all the numbers &le; ''m'' coprime with all the primes &le; ''p''. According to the M. O'Neill's article (p.10) there are <math>\textstyle\Phi(m,p) \in \Theta(m/\log p)</math> such numbers.
If each multiple is dealt with in '''<math>O(1)</math>''' time, this will translate into '''<math>O(m \log \log(m))</math>''' RAM machine operations (since we consider addition as an atomic operation). Indeed, mutable random-access arrays allow for that. Melissa O'Neill's article's stated goal was to show that so does efficient Priority Queue implementation in Haskell as well. But lists in Haskell are sequential, ''not'' random-access, and complexity of <code>minus(a,b)</code> is about '''<math>O(|a \cup b|)</math>''', i.e. here it is '''<math>O(|a|)</math>''' which is '''<math>O(m/\log(p))</math>''' according to the remark about the '''Φ'''-function in Melissa O'Neill's article.
 
   
It looks like <math>\sum_{i=1}^{k}{1/log(p_i)} = O(k/\log(k))</math>. Since the number of primes below ''m'' is '''<math>n = \pi(m) = O(m/\log(m))</math>''' by the ''prime number theorem'' (where <math>\pi(m)</math> is a prime counting function), there will be ''k = n'' multiples-removing steps in the algorithm; it means total complexity of '''<math>O(m k/\log(k)) = O(m^2/(\log(m))^2)</math>''', or '''<math>O(n^2)</math>''' in ''n'' primes produced - much much worse than the optimal '''<math>O(n \log(n) \log\log(n))</math>'''.
+
It looks like <math>\textstyle\sum_{i=1}^{n}{1/log(p_i)} = O(n/\log n)</math> for our intents and purposes. Since the number of primes below ''m'' is <math>n = \pi(m) = O(m/\log(m))</math> by the prime number theorem (where <math>\pi(m)</math> is a prime counting function), there will be ''n'' multiples-removing steps in the algorithm; it means total complexity of at least <math>O(m n/\log(n)) = O(m^2/(\log(m))^2)</math>, or <math>O(n^2)</math> in ''n'' primes produced - much much worse than the optimal <math>O(n \log(n) \log\log(n))</math>.
   
 
=== From Squares ===
 
=== From Squares ===
   
But we can start each step at the prime's ''square'', as its smaller multiples will be already processed 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 '''<math>k = \pi(\sqrt{m}) = O(2\sqrt{m}/\log(m))</math>'''. This does not in fact change the complexity of random-access code, but for lists it makes it '''<math>O(m^{1.5}/(\log m)^2)</math>''', or '''<math>O(n^{1.5}/\sqrt{\log n})</math>''' in ''n'' primes produced, showing an ''enormous'' speedup in practice:
+
But we can start each elimination step at a prime's square, as its smaller multiples will have been already produced and discarded on previous steps, as multiples of smaller primes. This means we can stop early now, when the prime's square reaches the top value ''m'', and thus cut the total number of steps to around <math>\textstyle n = \pi(m^{0.5}) = \Theta(2m^{0.5}/\log m)</math>. This does not in fact change the complexity of random-access code, but for lists it makes it <math>O(m^{1.5}/(\log m)^2)</math>, or <math>O(n^{1.5}/(\log n)^{0.5})</math> in ''n'' primes produced, a dramatic speedup:
 
<haskell>
 
<haskell>
primesToQ m = 2 : sieve [3,5..m] where
+
primesToQ m = eratos [2..m] where
sieve [] = []
+
eratos [] = []
sieve (p:xs) = p : sieve (xs `minus` [p*p,p*p+2*p..m])
+
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])
  +
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])
  +
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))
  +
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0]
 
</haskell>
 
</haskell>
   
Its empirical complexity is about <math>O(n^{1.45})</math>. This simple optimization of starting from a prime's square has dramatic effect here because our formulation is ''bounded'', in accordance with the original algorithm. This has the desired effect of ''stopping early'' and thus ''preventing'' the creation of all the ''extraneous'' multiples streams which start ''beyond'' the upper bound anyway, turning the unacceptably slow initial ''specification'' into a ''code'' yet-far-from-optimal and slow, but acceptably so, striking a good balance between clarity, succinctness and efficiency.
+
Its empirical complexity is around <math>O(n^{1.45})</math>. This simple optimization works here because this formulation is bounded (by an upper limit). To start late on a bounded sequence is to stop early (starting past end makes an empty sequence &ndash; ''see warning below''<sup><sub> 1</sub></sup>), thus preventing the creation of all the superfluous multiples streams which start above the upper bound anyway <small>(note that Turner's sieve is unaffected by this)</small>. This is acceptably slow now, striking a good balance between clarity, succinctness and efficiency.
  +
  +
<sup><sub>1</sub></sup><small>''Warning'': this is predicated on a subtle point of <code>minus xs [] = xs</code> definition being used, as it indeed should be. If the definition <code>minus (x:xs) [] = x:minus xs []</code> is used, the problem is back and the complexity is bad again.</small>
   
 
=== Guarded ===
 
=== 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'' - but ''only after'' we've went to the necessary trouble of explicitly ''stopping'' as soon as possible:
+
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'':
 
<haskell>
 
<haskell>
primesToG m = 2 : sieve [3,5..m] where
+
primesToG m = 2 : sieve [3,5..m] where
 
sieve (p:xs)
 
sieve (p:xs)
| p*p > m = p : xs
+
| p*p > m = p : xs
| True = p : sieve (xs `minus` [p*p,p*p+2*p..m])
+
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])
  +
-- p : sieve (xs `minus` map (p*) [p,p+2..])
  +
-- p : eulers (xs `minus` map (p*) (p:xs))
 
</haskell>
 
</haskell>
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.
+
(here we also dismiss all evens above 2 a priori.) 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.
   
 
=== Accumulating Array ===
 
=== Accumulating Array ===
   
So while <code>minus(a,b)</code> takes <math>O(|b|)</math> operations for random-access imperative arrays and about <math>O(|a|)</math> operations for lists here, using Haskell's immutable array for ''a'' one ''could'' expect the array update time to be indeed <math>O(|b|)</math> but it looks like it's not so:
+
So while <code>minus(a,b)</code> takes <math>O(|b|)</math> operations for random-access imperative arrays and about <math>O(|a|)</math> operations here for ordered increasing lists of numbers, using Haskell's immutable array for ''a'' one ''could'' expect the array update time to be nevertheless closer to <math>O(|b|)</math> if destructive update were used implicitly by compiler for an array being passed along as an accumulating parameter:
 
<haskell>
 
<haskell>
  +
{-# OPTIONS_GHC -O2 #-}
primesToA m = sieve 3 $ array (3,m) [(i,odd i) | i<-[3..m]]
 
  +
import Data.Array.Unboxed
  +
  +
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]
  +
:: UArray Int Bool)
 
where
 
where
sieve p a
+
sieve p a
| p*p>m = 2 : [i | (i,True) <- assocs a]
+
| p*p > m = 2 : [i | (i,True) <- assocs a]
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p,p*p+2*p..m]]
+
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]
| True = sieve (p+2) a
+
| otherwise = sieve (p+2) a
 
</haskell>
 
</haskell>
   
  +
Indeed for unboxed arrays, with the type signature added explicitly <small>(suggested by Daniel Fischer)</small>, the above code runs pretty fast, with empirical complexity of about ''<math>O(n^{1.15..1.45})</math>'' 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.
It's much slower than the above, though it ''should'' be running at optimal complexity on implementations which are able to properly use the destructive update here, for an array being passed along as an accumulating parameter, it seems.
 
   
How this implementation deficiency is to be overcome? 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.
+
How can we write code that we'd be certain about? One way is to use explicitly mutable monadic arrays ([[#Using Mutable Arrays|''see below'']]), but we can also think about it a little bit more on the functional side of things still.
   
 
=== Postponed ===
 
=== 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:
+
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 prematurely. Fixing this with explicit synchronization won't change complexity but will speed it up some more:
 
<haskell>
 
<haskell>
  +
primesPE1 = 2 : sieve [3..] primesPE1
primesPE () = 2 : primes'
 
  +
where
  +
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =
  +
h ++ sieve (t `minus` [q, q+p..]) ps
  +
-- h ++ turner [x|x<-t, rem x p /= 0] ps
  +
</haskell>
  +
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)
  +
where
  +
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =
  +
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t
  +
-- h ++ turner [x | x <- ys, rem x p /= 0] ...
  +
-->
  +
Inlining and fusing <code>span</code> and <code>(++)</code> we get:
  +
<haskell>
  +
primesPE = 2 : primes'
 
where
 
where
 
primes' = sieve [3,5..] 9 primes'
 
primes' = sieve [3,5..] 9 primes'
 
sieve (x:xs) q ps@ ~(p:t)
 
sieve (x:xs) q ps@ ~(p:t)
| x < q = x : sieve xs q ps
+
| x < q = x : sieve xs q ps
| True = sieve (xs `minus` [q,q+2*p..]) (head t^2) t
+
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t
 
</haskell>
 
</haskell>
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.
+
Since the removal of a prime's multiples here starts at the right moment, and not just from the right place, the code can 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 original formulation's extreme inefficiency.
   
 
=== Segmented ===
 
=== Segmented ===
Line 113: Line 179:
   
 
<haskell>
 
<haskell>
primesSE () = 2 : primes'
+
primesSE = 2 : primes'
where
+
where
 
primes' = sieve 3 9 primes' []
 
primes' = sieve 3 9 primes' []
sieve x q ~(p:ps) fs =
+
sieve x q ~(p:t) fs =
 
foldr (flip minus) [x,x+2..q-2]
 
foldr (flip minus) [x,x+2..q-2]
[[y+s,y+2*s..q] | (s,y) <- fs]
+
[[y+s, y+2*s..q] | (s,y) <- fs]
++ sieve (q+2) (head ps^2) ps
+
++ sieve (q+2) (head t^2) t
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])
+
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])
 
</haskell>
 
</haskell>
   
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. Rearranging the chain of subtractions into a subtraction of merged streams ''(see below)'' and using [http://ideone.com/pfREP tree-like folding] further speeds up the code and ''significantly'' improves its asymptotic behavior:
+
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.
  +
  +
====Segmented Tree-merging====
  +
Rearranging the chain of subtractions into a subtraction of merged streams ''([[#Linear merging|see below]])'' and using [[#Tree merging|tree-like folding]] structure, further [http://ideone.com/pfREP speeds up the code] and ''significantly'' improves its asymptotic time behavior (down to about <math>O(n^{1.28} empirically)</math>, space is leaking though):
  +
 
<haskell>
 
<haskell>
primesSTE () = 2 : primes'
+
primesSTE = 2 : primes'
where
+
where
primes' = sieve 3 9 primes' []
+
primes' = sieve 3 9 primes' []
sieve x q ~(p:ps) fs =
+
sieve x q ~(p:t) fs =
([x,x+2..q-2] `minus`
+
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])
foldt [[y+s,y+2*s..q] | (s,y) <- fs])
+
++ sieve (q+2) (head t^2) t
++ sieve (q+2) (head ps^2) ps
+
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])
 
 
 
foldt (a:b:c:xs) = foldt (union (union a b) c : pairs xs)
+
joinST (xs:t) = (union xs . joinST . pairs) t where
foldt [a,b] = union a b
+
pairs (xs:ys:t) = union xs ys : pairs t
foldt [a] = a
+
pairs t = t
foldt [] = []
+
joinST [] = []
pairs (a:b:xs) = union a b : pairs xs
 
pairs xs = xs
 
 
</haskell>
 
</haskell>
 
The advantage in working with 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.
 
   
 
=== Linear merging ===
 
=== 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 <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? With each prime's square passed over, there emerges 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, seen in his code presented in M. O'Neill's article, equivalent to:
  +
<haskell>
 
  +
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)
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).
 
  +
</haskell>
 
  +
or,
Here's the code, faster yet but still with about same time complexity of <math>O(n^{1.4})</math>:
 
   
 
<haskell>
 
<haskell>
  +
primesLME1 = 2 : primes' where
{-# OPTIONS_GHC -O2 -fno-cse #-}
 
  +
primes' = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- primes'])
primesLME () = 2 : ([3,5..] `minus`
 
  +
join [[p*p,p*p+2*p..] | p <- primes'])
 
  +
joinL ((x:xs):t) = x : union xs (joinL t)
where
 
primes' = 3 : ([5,7..] `minus`
 
join [[p*p,p*p+2*p..] | p <- primes'])
 
join ((x:xs):t) = x : union xs (join t)
 
 
</haskell>
 
</haskell>
   
  +
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 multiples 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, defining <code>joinL</code> (or <code>foldr</code>'s combining function) to produce part of its result ''before'' accessing the rest of its input (making it ''productive'').
The double primes feed is introduced here to prevent unneeded memoization and thus prevent memory leak, as per Melissa O'Neill's code, and is dependent on no expression sharing being performed by a compiler.
 
   
  +
Melissa O'Neill [http://hackage.haskell.org/packages/archive/NumberSieves/0.0/doc/html/src/NumberTheory-Sieve-ONeill.html introduced double primes feed] to prevent unneeded memoization (a memory leak). We can even do multistage. Here's the code, faster still and with radically reduced memory consumption, with empirical orders of growth of about ~ <math> n^{1.25..1.40}</math>:
=== 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):
 
   
 
<haskell>
 
<haskell>
  +
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))
{-# OPTIONS_GHC -O2 -fno-cse #-}
 
  +
primesTME () = 2 : ([3,5..] `minus`
 
  +
_Y :: (t -> t) -> t
join [[p*p,p*p+2*p..] | p <- primes'])
 
  +
_Y g = g (_Y g) -- multistage, non-sharing, recursive
where
 
  +
-- g x where x = g x -- two stages, sharing, corecursive
primes' = 3 : ([5,7..] `minus`
 
join [[p*p,p*p+2*p..] | p <- primes'])
 
join ((x:xs):t) = x : union xs (join (pairs t))
 
pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t
 
 
</haskell>
 
</haskell>
   
  +
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).
It is [http://ideone.com/p0e81 very fast], running at speeds and empirical complexities comparable with the code from Melissa O'Neill's article (about <math>O(n^{1.2})</math> in number of primes ''n'' produced).
 
   
  +
This allows the <code>primesLME</code> stream to be discarded immediately as it is being consumed by its consumer. With <code>primes'</code> from <code>primesLME1</code> definition above it is impossible, as each produced element of <code>primes'</code> is needed later as input to the same <code>primes'</code> corecursive stream definition. So the <code>primes'</code> stream feeds in a loop into itself, and thus is retained in memory. With multistage production, each stage feeds into its consumer above it at the square of its current element which can be immediately discarded after it's been consumed. <code>(3:)</code> jump-starts the whole thing.
For aesthetic purposes the above can be [http://ideone.com/qpnqe rewritten as follows], using explicated [[Fold#Tree-like_folds|infinite tree-like folding]]:
 
  +
  +
=== Tree merging ===
  +
Moreover, it can be changed into a '''''tree''''' structure. This idea [http://www.haskell.org/pipermail/haskell-cafe/2007-July/029391.html is due to Dave Bayer] and [[Prime_numbers_miscellaneous#Implicit_Heap|Heinrich Apfelmus]]:
   
 
<haskell>
 
<haskell>
  +
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))
primes = 2 : g (fix g)
 
where
 
g xs = 3 : gaps 5 (foldi (\(x:xs) ys -> x:union xs ys) []
 
[[x*x, x*x+2*x..] | x <- xs])
 
   
  +
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- ~= nub.sort.concat
fix g = xs where xs = g xs
 
  +
where pairs (xs:ys:t) = union xs ys : pairs t
   
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- equivalent to
+
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, when
| True = gaps (k+2) xs -- [k,k+2..]`minus`s, k<=x
+
| True = gaps (k+2) xs -- k<=x && null(s\\[k,k+2..])
 
</haskell>
 
</haskell>
  +
  +
This code is [http://ideone.com/p0e81 pretty fast], running at speeds and empirical complexities comparable with the code from Melissa O'Neill's article (about <math>O(n^{1.2})</math> in number of primes ''n'' produced).
  +
  +
As an aside, <code>joinT</code> is equivalent to [[Fold#Tree-like_folds|infinite tree-like folding]] <code>foldi (\(x:xs) ys-> x:union xs ys) []</code>:
  +
  +
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]
   
 
=== Tree merging with Wheel ===
 
=== 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 the same):
+
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, for first few million primes):
   
 
<haskell>
 
<haskell>
  +
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel
{-# OPTIONS_GHC -O2 -fno-cse #-}
 
  +
. joinT . hitsW 11 wheel)
primesTMWE () = 2:3:5:7: gaps 11 wheel (join $ roll 11 wheel primes')
 
where
+
  +
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s
primes' = 11: gaps 13 (tail wheel) (join $ roll 11 wheel primes')
 
join ((x:xs): ~(ys:zs:t)) = x : union xs (union ys zs)
+
| otherwise = gapsW (k+d) w cs -- k==c
`union` join (pairs t)
+
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s
pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t
+
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w)
gaps k ws@(w:t) cs@(c:u) | k==c = gaps (k+w) t u
+
: hitsW (k+d) w ps -- k==p
  +
wheel = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:
| True = k : gaps (k+w) t cs
 
  +
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel
roll k ws@(w:t) ps@(p:u) | k==p = scanl (\c d->c+p*d) (p*p) ws
 
: roll (k+w) t u
 
| True = roll (k+w) t ps
 
wheel = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:
 
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel
 
 
</haskell>
 
</haskell>
   
  +
====Above Limit====
 
  +
====Above Limit - Offset Sieve====
Another task is to produce primes above a given number (not having to find out their ordinal numbers).
 
  +
Another task is to produce primes above a given value:
 
<haskell>
 
<haskell>
 
{-# OPTIONS_GHC -O2 -fno-cse #-}
 
{-# OPTIONS_GHC -O2 -fno-cse #-}
primesFromTMWE a0 = (if a0 <= 2 then [2] else [])
+
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11]
++ (gaps a wh' $ compositesFrom a)
+
++ gapsW a wh' (compositesFrom a)
 
where
 
where
(a,wh') = rollFrom (snap (max 3 a0) 3 2)
+
(a,wh') = rollFrom (snapUp (max 3 m) 3 2)
(h,p':t) = span (< z) primes' -- p < z => p*p<=a
+
(h,p':t) = span (< z) $ drop 4 primes -- p < z => p*p<=a
z = ceiling $ sqrt $ fromIntegral a + 1 -- p'>=z => p'*p'>a
+
z = ceiling $ sqrt $ fromIntegral a + 1 -- p'>=z => p'*p'>a
  +
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p']]
  +
: [multsOf p (p*p) | p <- t] )
   
  +
snapUp v o step = v + (mod (o-v) step) -- full steps from o
compositesFrom a =
 
foldi union' [] (foldi union [] [multsOf p a | p <- h++[p']]
+
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $
: [multsOf p (p*p) | p <- t])
+
where -- scanl (+) x wh
  +
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from
primes' = gaps 11 wheel (foldi union' []
 
[multsOf p (p*p) | p <- primes''])
 
primes'' = 11: gaps 13 (tail wheel) (foldi union' []
 
[multsOf p (p*p) | p <- primes''])
 
union' (x:xs) ys = x : union xs ys
 
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- (p*)<$>
 
where -- scanl (+) x wh
 
(x,wh) = rollFrom (snap from p (2*p) `div` p)
 
 
gaps k ws@(w:t) cs@(c:u) | k==c = gaps (k+w) t u
 
| True = k : gaps (k+w) t cs
 
snap v origin step = if r==0 then v else v+(step-r)
 
where r = mod (v-origin) step
 
 
wheelNums = scanl (+) 0 wheel
 
wheelNums = scanl (+) 0 wheel
wheel = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:
 
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel
 
 
rollFrom n = go wheelNums wheel
 
rollFrom n = go wheelNums wheel
where m = (n-11) `mod` 210
+
where m = (n-11) `mod` 210
 
go (x:xs) ws@(w:ws') | x < m = go xs ws'
 
go (x:xs) ws@(w:ws') | x < m = go xs ws'
| True = (n+x-m, ws) -- (x >= m)
+
| True = (n+x-m, ws) -- (x >= m)
 
</haskell>
 
</haskell>
   
  +
A certain preprocessing delay makes it worthwhile when producing more than just a few primes, otherwise it degenerates into simple [[#Optimal trial division|trial division]], which is then ought to be used directly:
This uses the [[Fold#Tree-like_folds|infinite-tree folding]] <code>foldi</code> with plain <code>union</code> where heads are unordered, and back with <code>union'</code> above that. A certain preprocessing delay makes it worthwhile when producing more than just a few primes.
 
  +
  +
<haskell>
  +
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:
  +
  +
<haskell>
  +
import Data.List -- based on http://stackoverflow.com/a/1140100
  +
import qualified Data.Map as M
  +
  +
primesMPE :: [Integer]
  +
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;
  +
where -- decoupled primes loop feed
  +
prs = 3:mkPrimes 5 M.empty prs 9
  +
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of
  +
(False, (n', skips)) | n == n' ->
  +
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q
  +
_ -> if n<q
  +
then n : mkPrimes (n+2) m ps q
  +
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)
  +
  +
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m
  +
addSkips = foldl' . addSkip
  +
</haskell>
   
 
== Turner's sieve - Trial division ==
 
== 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:
+
David Turner's original 1975 formulation ''(SASL Language Manual, 1975)'' replaces non-standard <code>minus</code> in the sieve of Eratosthenes by stock list comprehension with <code>rem</code> filtering, turning it into a trial division algorithm:
   
 
<haskell>
 
<haskell>
-- unbounded sieve, premature filters
+
-- unbounded sieve, premature filters
primesT () = 2 : sieve [3,5..] where
+
primesT = sieve [2..]
  +
where
sieve (p:xs) = p : sieve [x | x<-xs, rem x p /= 0]
 
-- filter ((/=0).(`rem`p)) xs
+
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
  +
-- map fst . tail
  +
-- $ iterate (\(_,p:xs)->(p,[x | x <- xs, rem x p /= 0])) (1,[2..])
 
</haskell>
 
</haskell>
   
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 '''1001'''st prime (<code>7927</code>), '''1000''' filters are used, when in fact just the first '''24''' are needed (up to <code>89</code>'s filter only). Operational overhead is enormous here.
+
This creates many superfluous implicit filters, because they are created prematurely. To be admitted as prime, ''each number'' will be ''tested for divisibility'' here by all its preceding primes, while just those not greater than its square root would suffice. To find e.g. the '''1001'''st prime (<code>7927</code>), '''1000''' filters are used, when in fact just the first '''24''' are needed (up to <code>89</code>'s filter only). Operational overhead here is huge.
   
 
=== Guarded Filters ===
 
=== Guarded Filters ===
When we force ourselves away from the ''Quest for a Mythical One-Liner'' it really ought to be written ''at least'' as bounded and guarded variety (if not abandoned right away in favor of algorithmically superior sieve of Eratosthenes), yet again achieving the ''miraculous'' complexity improvement from above quadratic to about <math>O(n^{1.45})</math> empirically (in ''n'' primes produced):
+
But this really ought to be changed into bounded and guarded variant, [[#From Squares|again achieving]] the ''"miraculous"'' complexity improvement from above quadratic to about <math>O(n^{1.45})</math> empirically (in ''n'' primes produced):
   
 
<haskell>
 
<haskell>
primesToGT m = 2 : sieve [3,5..m] where
+
primesToGT m = sieve [2..m]
  +
where
 
sieve (p:xs)
 
sieve (p:xs)
| p*p > m = p : xs
+
| p*p > m = p : xs
| True = p : sieve [x | x<-xs, rem x p /= 0]
+
| True = p : sieve [x | x <- xs, rem x p /= 0]
  +
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail
  +
-- $ iterate (\(_,p:xs)->(p,[x | x <- xs, rem x p /= 0])) (1,[2..m])
 
</haskell>
 
</haskell>
   
 
=== Postponed Filters ===
 
=== Postponed Filters ===
or ''better yet'' as unbounded, postponed variety:
+
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:
 
<haskell>
 
<haskell>
  +
primesPT1 = 2 : sieve primesPT1 [3..]
primesPT () = 2 : primes'
 
  +
where
  +
sieve (p:ps) xs = let (h,t) = span (< p*p) xs
  +
in h ++ sieve ps [x | x<-t, rem x p /= 0]
  +
-- fix $ (2:) . concat .
  +
-- unfoldr (\(xs,p:ps)->let (h,t)=span (< p*p) xs in
  +
-- Just(h,([x | x <- t, rem x p /= 0],ps))) . ((,) [3..])
  +
</haskell>
  +
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:
  +
<haskell>
  +
primesPT = 2 : primes'
 
where
 
where
 
primes' = sieve [3,5..] 9 primes'
 
primes' = sieve [3,5..] 9 primes'
 
sieve (x:xs) q ps@ ~(p:t)
 
sieve (x:xs) q ps@ ~(p:t)
| x < q = x : sieve xs q ps
+
| x < q = x : sieve xs q ps
| True = sieve [x | x<-xs, rem x p /= 0] (head t^2) t
+
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t
 
</haskell>
 
</haskell>
creating here as well the linear nested filters structure at run-time, ''(...(([3,5..] |> filterBy 3) |> filterBy 5)...)'' (with <code>|></code> defined as <code>x |> f = f x</code>), each filter started at its proper moment.
+
creating here [[#Linear merging |as well]] the linear nested structure at run-time, <code>(...(([3,5..] >>= filterBy [3]) >>= filterBy [5])...)</code>, where <code>filterBy ds n = [n | noDivs n ds]</code> (see <code>noDivs</code> definition below) &thinsp;&ndash;&thinsp; but unlike the original code, each filter being created at its proper moment, not sooner than the prime's square is seen.
   
=== Optimal trial divison ===
+
=== Optimal trial division ===
   
 
The above is equivalent to the traditional formulation of trial division,
 
The above is equivalent to the traditional formulation of trial division,
 
<haskell>
 
<haskell>
  +
ps = 2 : [i | i <- [3..],
isPrime primes n = foldr (\p r -> p*p > n || (rem n p /= 0 && r))
 
True primes
+
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]
primes = 2 : filter (isPrime primes) [3..]
 
 
</haskell>
 
</haskell>
  +
or,
except that this one is rechecking for each candidate which primes to use, which will be the same prefix of the primes list being built, for all the candidate numbers in the ever increasing spans between the successive primes squares.
 
  +
<haskell>
  +
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs
  +
-- primes = filter (`noDivs`[2..]) [2..]
  +
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]
  +
isPrime n = n > 1 && noDivs n primesTD
  +
</haskell>
  +
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.
  +
  +
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].
   
 
=== Segmented Generate and Test ===
 
=== Segmented Generate and Test ===
  +
Next we turn [[#Postponed Filters |the list of filters]] into one filter by an ''explicit'' list, each one in a progression of prefixes of the primes list. This seems to eliminate most recalculations, explicitly filtering composites out from batches of odds between the consecutive squares of primes.
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:
 
 
<haskell>
 
<haskell>
  +
import Data.List
primesST () = 2 : primes'
 
  +
  +
primesST = 2 : oddprimes
 
where
 
where
primes' = sieve 3 9 primes' 0
+
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...
sieve x q ~(_:t) k = let fs = take k primes' in
+
sieve x q ~(_:t) (fs:ft) =
[n | n <- [x,x+2..q-2], and [rem n f/=0 | f <- fs]]
+
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]
++ sieve (q+2) (head t^2) t (k+1)
+
++ sieve (q+2) (head t^2) t ft
 
</haskell>
 
</haskell>
This seems to eliminate most recalculations, explicitly filtering composites out from batches of odds between the consecutive squares of primes.
 
   
All these variants of course being variations of trial division &ndash; 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) &ndash; are thus of principally worse complexities than that of Sieve of Eratosthenes; yet one improved over the other just by following the proper definition of the sieve as being bounded, simply with guarded formulation, before resorting to using brittle implementations of complex data structures with unclear performance guarantees.
 
   
 
==== Generate and Test Above Limit ====
 
==== Generate and Test Above Limit ====
   
The following will start the segmented Turner sieve at the right place, using any primes list it's supplied with (e.g. [[Prime_numbers#Tree_merging_with_Wheel | TMWE]] etc.), demand computing it up to the square root of any prime it'll produce:
+
The following will start the segmented Turner sieve at the right place, using any primes list it's supplied with (e.g. [[#Tree_merging_with_Wheel | TMWE]] etc.) or itself, as shown, demand computing it just up to the square root of any prime it'll produce:
   
 
<haskell>
 
<haskell>
  +
primesFromST m | m > 2 =
primesSTFrom primes m
 
| m>2 = sieve (m`div`2*2+1) (head ps^2) (tail ps) (length h-1)
+
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)
 
where
 
where
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) primes
+
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes
sieve x q ps k = let fs = take k $ tail primes in
+
sieve x q ps (fs:ft) =
[n | n <- [x,x+2..q-2], and [rem n f /= 0 | f <- fs]]
+
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]
++ sieve (q+2) (head ps^2) (tail ps) (k+1)
+
++ sieve (q+2) (head ps^2) (tail ps) ft
  +
oddprimes = 3 : primesFromST 5 -- odd primes
 
</haskell>
 
</haskell>
   
This is usually faster than testing candidate numbers for divisibility [[#Optimal trial division|one by one]] which has to re-fetch anew the needed prime factors to test by, for each candidate. Faster is the [[99_questions/Solutions/39#Solution_4.|offset sieve of Eratosthenes on odds]], and yet faster the above one, [[Prime_numbers#Above_limit| w/ wheel optimization]].
+
This is usually faster than testing candidate numbers for divisibility [[#Optimal trial division|one by one]] which has to re-fetch anew the needed prime factors to test by, for each candidate. Faster is the [[99_questions/Solutions/39#Solution_4.|offset sieve of Eratosthenes on odds]], and yet faster the one [[#Above_Limit_-_Offset_Sieve|w/ wheel optimization]], on this page.
   
 
=== Conclusions ===
 
=== Conclusions ===
  +
All these variants being variations of trial division, finding out primes by direct divisibility testing of every candidate 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 principally of worse complexity than that of Sieve of Eratosthenes.
So it really pays off to analyse the code properly instead of just labeling it ''"naive"''. BTW were this divisibility testing ''somehow turned'' into an '''O(1)''' operation, e.g. by some kind of massive parallelization, the overall complexity would drop to '''O(n)'''. It's the sequentiality of testing that's the culprit. Though of course the proper multiples-removing S. of E. is a better candidate for parallelization.
 
 
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''? We'll leave that as an open question.
 
   
So the initial Turner code is just a ''one-liner'' that ought to have been regarded as ''specification'' only, in the first place, not a code to be executed as such. The reason it was taught that way is probably so that it could provoke this discussion among the students. ''To regard it as plain executable code is what's been naive all along''.
+
The initial code is just a one-liner that ought to have been regarded as ''executable specification'' in the first place. It can easily be improved quite significantly with a simple use of bounded, guarded formulation to limit the number of filters it creates, or by postponement of filter creation.
   
 
== Euler's Sieve ==
 
== Euler's Sieve ==
Line 339: Line 438:
   
 
<haskell>
 
<haskell>
primesEU () = 2 : euler [3,5..] where
+
primesEU = 2 : eulers [3,5..] where
euler (p:xs) = p : euler (xs `minus` map (p*) (p:xs))
+
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))
  +
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])
 
</haskell>
 
</haskell>
   
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, under the simple scheme of producing the multiples by multiplication.
   
 
=== Wheeled list representation ===
 
=== Wheeled list representation ===
Line 349: Line 453:
 
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:
 
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:
 
<haskell>
 
<haskell>
  +
{- fromElt (x,i) = x : fromElt (x + i,i)
 
{- fromElt (x,i) = x : fromElt (x + i,i)
 
 
=== iterate (+ i) x
 
=== iterate (+ i) x
 
[n..] === fromElt (n,1)
 
[n..] === fromElt (n,1)
Line 357: Line 460:
 
=== fromSpan ([n,n+2],4) -}
 
=== fromSpan ([n,n+2],4) -}
   
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)
+
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)
   
{- === concat $ iterate (map (+ i)) xs
+
{- === concat $ iterate (map (+ i)) xs
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i)
+
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i)
fromSpan (xs,i) `minus` fromSpan (ys,i)
+
fromSpan (xs,i) `minus` fromSpan (ys,i)
=== fromSpan (xs `minus` ys, i)
+
=== fromSpan (xs `minus` ys, i)
map (p*) (fromSpan (xs,i))
+
map (p*) (fromSpan (xs,i))
=== fromSpan (map (p*) xs, p*i)
+
=== fromSpan (map (p*) xs, p*i)
fromSpan (xs,i) === forall (p > 0).
+
fromSpan (xs,i) === forall (p > 0).
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}
+
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}
   
spanSpecs = iterate eulerStep ([2],1)
+
spanSpecs = iterate eulerStep ([2],1)
eulerStep (xs@(p:_), i) =
+
eulerStep (xs@(p:_), i) =
 
( (tail . concat . take p . iterate (map (+ i))) xs
 
( (tail . concat . take p . iterate (map (+ i))) xs
 
`minus` map (p*) xs, p*i )
 
`minus` map (p*) xs, p*i )
   
{- > mapM_ print $ take 4 spanSpecs
+
{- > mapM_ print $ take 4 spanSpecs
 
([2],1)
 
([2],1)
 
([3],2)
 
([3],2)
Line 383: Line 486:
   
 
<haskell>
 
<haskell>
eulerPrimesTo m = if m > 1 then go ([2],1) else []
+
eulerPrimesTo m = if m > 1 then go ([2],1) else []
 
where
 
where
 
go w@((p:_), _)
 
go w@((p:_), _)
Line 396: Line 499:
 
=== Generating Segments of Primes ===
 
=== Generating Segments of Primes ===
   
The 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:
+
The sieve of Eratosthenes' [[#Segmented|removal of multiples on each segment of odds]] can be done by actually marking them in an array, instead of manipulating ordered lists, and can be further sped up more than twice by working with odds only:
   
 
<haskell>
 
<haskell>
  +
import Data.Array.Unboxed
primesSA () = 2 : prs
 
  +
where
 
  +
primesSA :: [Int]
  +
primesSA = 2 : prs
  +
where
 
prs = 3 : sieve prs 3 []
 
prs = 3 : sieve prs 3 []
sieve (p:ps) x fs = [i*2 + x | (i,e) <- assocs a, e]
+
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a]
++ sieve ps (p*p) fs'
+
++ sieve ps (p*p) ((p,0) :
  +
[(s, rem (y-q) s) | (s,y) <- fs])
 
where
 
where
q = (p*p-x)`div`2
+
q = (p*p-x)`div`2
  +
a :: UArray Int Bool
fs' = (p,0) : [(s, rem (y-q) s) | (s,y) <- fs]
 
a = accumArray (\ b c -> False) True (1,q-1)
+
a = accumArray (\ b c -> False) True (1,q-1)
[(i,()) | (s,y) <- fs, i <- [y+s,y+s+s..q]]
+
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]]
 
</haskell>
 
</haskell>
   
  +
Runs significantly faster than [[#Tree merging with Wheel|TMWE]] and with better empirical complexity, of about <math>O(n^{1.10..1.05})</math> in producing first few millions of primes, with constant memory footprint.
Apparently, arrays are ''fast''. The above is the fastest code of all presented so far. When run on ''[http://ideone.com/willness/primes Ideone.com]'' it is somewhat faster than [[#Tree Merging With Wheel|Tree Merging With Wheel]] in producing first few million primes, but is very much unacceptable in its memory consumption which grows faster than O(<math>{n}</math>), quickly getting into tens and hundreds of MBs.
 
   
 
=== Calculating Primes Upto a Given Value ===
 
=== Calculating Primes Upto a Given Value ===
  +
  +
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):
   
 
<haskell>
 
<haskell>
  +
{-# OPTIONS_GHC -O2 #-}
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]
 
  +
import Data.Array.Unboxed
where
 
  +
  +
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]
  +
where
 
ar = f 5 $ accumArray (\ a b -> False) True (3,n)
 
ar = f 5 $ accumArray (\ a b -> False) True (3,n)
 
[(i,()) | i <- [9,15..n]]
 
[(i,()) | i <- [9,15..n]]
Line 423: Line 535:
 
| True = if null x then a' else f (head x) a'
 
| True = if null x then a' else f (head x) a'
 
where q = p*p
 
where q = p*p
a'= a // [(i,False) | i <- [q,q+2*p..n]]
+
a' :: UArray Int Bool
  +
a'= a // [(i,False) | i <- [q, q+2*p..n]]
 
x = [i | i <- [p+2,p+4..n], a' ! i]
 
x = [i | i <- [p+2,p+4..n], a' ! i]
 
</haskell>
 
</haskell>
Line 430: Line 543:
   
 
<haskell>
 
<haskell>
primesFromToA a b = (if a<3 then [2] else [])
+
primesFromToA a b = (if a<3 then [2] else [])
 
++ [i | i <- [o,o+2..b], ar ! i]
 
++ [i | i <- [o,o+2..b], ar ! i]
where
+
where
 
o = max (if even a then a+1 else a) 3
 
o = max (if even a then a+1 else a) 3
r = floor.sqrt.fromInteger $ b+1
+
r = floor . sqrt $ fromIntegral b + 1
 
ar = accumArray (\a b-> False) True (o,b)
 
ar = accumArray (\a b-> False) True (o,b)
 
[(i,()) | p <- [3,5..r]
 
[(i,()) | p <- [3,5..r]
Line 454: Line 567:
   
 
This method implements the Sieve of Eratosthenes, similar to how you might do it
 
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 bit-packed) array for the whole sequence produced.
+
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.
   
 
<haskell>
 
<haskell>
Line 462: Line 575:
 
import Data.Array.Unboxed
 
import Data.Array.Unboxed
   
primesToNA :: Int -> UArray Int Bool
+
sieveUA :: Int -> UArray Int Bool
primesToNA n = runSTUArray sieve where
+
sieveUA top = runSTUArray $ do
  +
let m = (top-1) `div` 2
sieve = do
 
  +
r = floor . sqrt $ fromIntegral top + 1
let m = (n-1)`div`2
 
a <- newArray (1,m) True :: ST s (STUArray s Int Bool)
+
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)
  +
forM_ [1..r `div` 2] $ \i -> do
let sr = floor . (sqrt::Double->Double) $ fromIntegral n+1
 
  +
isPrime <- readArray sieve i
forM_ [1..sr`div`2] $ \i -> do
 
let ii = 2*i*(i+1) -- == ((2*i+1)^2-1)`div`2
+
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)
  +
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do
si <- readArray a i
 
  +
writeArray sieve j False
when si $
 
  +
return sieve
forM_ [ii,ii+i+i+1..m] $ \j -> writeArray a j False
 
return a
 
 
 
primesToN :: Int -> [Int]
+
primesToUA :: Int -> [Int]
primesToN n = 2:[i*2+1 | (i,True) <- assocs . primesToNA $n]
+
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]
 
</haskell>
 
</haskell>
   
Its empirical time complexity is improving with ''n'' (number of primes produced) from '''<math>O(n^{1.25})</math>''' through '''<math>O(n^{1.20})</math>''' towards '''<math>O(n^{1.16})</math>'''. The reference [http://ideone.com/FaPOB C++ vector-based implementation] exhibits this improvement in empirical time complexity too, from '''<math>O(n^{1.5})</math>''' gradually towards '''<math>O(n^{1.12})</math>''', where tested ''(which might be interpreted as evidence towards the expected [http://en.wikipedia.org/wiki/Computation_time#Linearithmic.2Fquasilinear_time quasilinearithmic] '''<math>O(n \log(n)\log(\log n))</math>''' time complexity)''.
+
Its [http://ideone.com/KwZNc empirical time complexity] is improving with ''n'' (number of primes produced) from above <math>O(n^{1.20})</math> towards <math>O(n^{1.16})</math>. The reference [http://ideone.com/FaPOB C++ vector-based implementation] exhibits this improvement in empirical time complexity too, from <math>O(n^{1.5})</math> gradually towards <math>O(n^{1.12})</math>, where tested ''(which might be interpreted as evidence towards the expected [http://en.wikipedia.org/wiki/Computation_time#Linearithmic.2Fquasilinear_time quasilinearithmic] <math>O(n \log(n)\log(\log n))</math> time complexity)''.
   
 
=== Bitwise prime sieve with Template Haskell ===
 
=== Bitwise prime sieve with Template Haskell ===
Line 558: Line 670:
 
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]
 
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]
 
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]
 
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]
  +
  +
== One-liners ==
  +
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].
   
 
== External links ==
 
== External links ==
 
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip
 
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip
 
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill.
 
: 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 that file for your projects: it's broken and works for primes only by a lucky chance.
+
: 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 [http://www.mail-archive.com/haskell-cafe@haskell.org/msg54618.html haskell-cafe] mailing list, and fixed by Bertram Felgenhauer.
   
 
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.
 
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.

Revision as of 20:46, 2 September 2014

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).

Prime Number Resources

  • HackageDB packages:
    • arithmoi: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...
    • Numbers: An assortment of number theoretic functions.
    • NumberSieves: Number Theoretic Sieves: primes, factorization, and Euler's Totient.
    • primes: Efficient, purely functional generation of prime numbers.
  • Papers:
    • 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.

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

   P  = {nN2 : (∀ mN2) ((m | n) ⇒ m = n)}
= {nN2 : (∀ mN2) (m×mn ⇒ ¬(m | n))}
= N2 \ {n×m : n,mN2}
= N2 \ { {n×m : mNn} : nN2 }
= N2 \ { {n×n, n×n+n, n×n+2×n, ...} : nN2 }
= N2 \ { {n×n, n×n+n, n×n+2×n, ...} : nP }
  where     Nk = {nN : n ≥ k}

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.

Sieve of Eratosthenes

The sieve of Eratosthenes calculates primes as integers above 1 that are not multiples of primes, i.e. not composite — whereas composites are found as a union of 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):

primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])

-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy
--   under n (minus a b) == under n a \\ under n b
--   under n (union a b) == nub . sort $ under n a ++ under n b
--   under n . _U == nub . sort . concat . map (under n)

The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.

_U can be defined as a folding of (\(x:xs) -> (x:) . union xs), or it can use an Bool array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.

Stepwise development follows (the fully developed version is here).

Initial definition

To start with, the sieve of Eratosthenes can be genuinely represented by

-- genuine yet wasteful sieve of Eratosthenes
primesTo m = eratos [2..m]  where
   eratos []     = []
   eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))  
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0]

This should be regarded more like a specification, not a code. It runs at empirical orders of growth 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 constant increments, equal to that prime.

The canonical list-difference minus and duplicates-removing union functions dealing with ordered increasing lists (cf. Data.List.Ordered package) are:

-- ordered lists, difference and union
minus (x:xs) (y:ys) = case (compare x y) of 
           LT -> x : minus  xs  (y:ys)
           EQ ->     minus  xs     ys 
           GT ->     minus (x:xs)  ys
minus  xs     _     = xs
union (x:xs) (y:ys) = case (compare x y) of 
           LT -> x : union  xs  (y:ys)
           EQ -> x : union  xs     ys 
           GT -> y : union (x:xs)  ys
union  xs     []    = xs
union  []     ys    = ys

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

Analysis

So for each newly found prime the sieve discards its multiples, enumerating them by counting up in steps of p. There are thus multiples generated and eliminated for each prime, and multiples in total, with duplicates, by virtues of prime harmonic series.

If each multiple is dealt with in time, this will translate into 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 by the prime number theorem (where is a prime counting function), there will be n multiples-removing steps in the algorithm; it means total complexity of at least , or in n primes produced - much much worse than the optimal .

From Squares

But we can start each elimination step at a prime's square, as its smaller multiples will have been already produced and discarded on previous steps, as multiples of smaller primes. This means we can stop early now, 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 , or in n primes produced, a dramatic speedup:

primesToQ m = eratos [2..m]  where
   eratos []     = []
   eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0]

Its empirical complexity is around . This simple optimization works here because this formulation is bounded (by an upper limit). To start late on a bounded sequence is to stop early (starting past end makes an empty sequence – see warning below 1), thus preventing the creation of all the superfluous multiples streams which start above the upper bound anyway (note that Turner's sieve is unaffected by this). This is acceptably slow now, striking a good balance between clarity, succinctness and efficiency.

1Warning: 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.

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:

primesToG m = 2 : sieve [3,5..m]  where
    sieve (p:xs) 
       | p*p > m   = p : xs
       | otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])
                  -- p : sieve (xs `minus` map (p*) [p,p+2..])
                  -- p : eulers (xs `minus` map (p*) (p:xs))

(here we also dismiss all evens above 2 a priori.) 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.

Accumulating Array

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

{-# OPTIONS_GHC -O2 #-}
import Data.Array.Unboxed

primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]
                        :: UArray Int Bool)
  where
    sieve p a 
      | p*p > m   = 2 : [i | (i,True) <- assocs a]
      | a!p       = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]
      | otherwise = sieve (p+2) a

Indeed for unboxed arrays, with the type signature added explicitly (suggested by Daniel Fischer), the above code runs pretty fast, with empirical complexity of about 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.

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 prematurely. Fixing this with explicit synchronization won't change complexity but will speed it up some more:

primesPE1 = 2 : sieve [3..] primesPE1 
  where 
    sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =
                   h ++ sieve (t `minus` [q, q+p..]) ps
                -- h ++ turner [x|x<-t, rem x p /= 0] ps

Inlining and fusing span and (++) we get:

primesPE = 2 : primes'
  where 
    primes' = sieve [3,5..] 9 primes'
    sieve (x:xs) q ps@ ~(p:t)
      | x < q     = x : sieve xs q ps
      | otherwise =     sieve (xs `minus` [q, q+2*p..]) (head t^2) t

Since the removal of a prime's multiples here starts at the right moment, and not just from the right place, the code can 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 original formulation's extreme inefficiency.

Segmented

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

primesSE = 2 : primes'
  where
    primes' = sieve 3 9 primes' []
    sieve x q ~(p:t) fs = 
        foldr (flip minus) [x,x+2..q-2] 
                           [[y+s, y+2*s..q] | (s,y) <- fs]
        ++ sieve (q+2) (head t^2) t
                ((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])

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.

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 , space is leaking though):

primesSTE = 2 : primes' 
  where                  
    primes' = sieve 3 9 primes' []
    sieve x q ~(p:t) fs = 
        ([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])
        ++ sieve (q+2) (head t^2) t
                   ((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])
    
joinST (xs:t) = (union xs . joinST . pairs) t  where
    pairs (xs:ys:t) = union xs ys : pairs t
    pairs t         = t
joinST []     = []

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? With each prime's square passed over, there emerges 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, seen in his code presented in M. O'Neill's article, equivalent to:

primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)

or,

primesLME1 = 2 : primes'  where
    primes' = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- primes'])
    
joinL ((x:xs):t) = x : union xs (joinL t)

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 multiples 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, defining joinL (or foldr's combining function) to produce part of its result before accessing the rest of its input (making it productive).

Melissa O'Neill introduced double primes feed to prevent unneeded memoization (a memory leak). We can even do multistage. Here's the code, faster still and with radically reduced memory consumption, with empirical orders of growth of about ~ :

primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))

_Y   :: (t -> t) -> t
_Y g = g (_Y g)                -- multistage, non-sharing, recursive
       -- g x where x = g x    -- two stages, sharing, corecursive

_Y is a non-sharing fixpoint combinator, here arranging for a recursive "telescoping" multistage primes production (a tower of producers).

This allows the primesLME stream to be discarded immediately as it is being consumed by its consumer. With primes' from primesLME1 definition above it is impossible, as each produced element of primes' is needed later as input to the same primes' corecursive stream definition. So the primes' stream feeds in a loop into itself, and thus is retained in memory. With multistage production, each stage feeds into its consumer above it at the square of its current element which can be immediately discarded after it's been consumed. (3:) jump-starts the whole thing.

Tree merging

Moreover, it can be changed into a tree structure. This idea is due to Dave Bayer and Heinrich Apfelmus:

primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))

joinT ((x:xs):t) = x : (union xs . joinT . pairs) t  -- ~= nub.sort.concat
  where  pairs (xs:ys:t) = union xs ys : pairs t 

gaps k s@(x:xs) | k<x  = k:gaps (k+2) s    -- ~= [k,k+2..]\\s, when
                | True =   gaps (k+2) xs   --   k<=x && null(s\\[k,k+2..])

This code is pretty fast, running at speeds and empirical complexities comparable with the code from Melissa O'Neill's article (about in number of primes n produced).

As an aside, joinT is equivalent to infinite tree-like folding foldi (\(x:xs) ys-> x:union xs ys) []:

tree-like folding

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, for first few million primes):

primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail  . gapsW 11 wheel 
                                    . joinT . hitsW 11 wheel)
    
gapsW k (d:w) s@(c:cs) | k < c     = k : gapsW (k+d) w s
                       | otherwise =     gapsW (k+d) w cs      -- k==c
hitsW k (d:w) s@(p:ps) | k < p     =     hitsW (k+d) w s
                       | otherwise = scanl (\c d->c+p*d) (p*p) (d:w) 
                                       : hitsW (k+d) w ps      -- k==p 
wheel = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:
        4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel


Above Limit - Offset Sieve

Another task is to produce primes above a given value:

{-# OPTIONS_GHC -O2 -fno-cse #-}
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] 
                          ++ gapsW a wh' (compositesFrom a)
  where
    (a,wh') = rollFrom (snapUp (max 3 m) 3 2)
    (h,p':t) = span (< z) $ drop 4 primes           -- p < z => p*p<=a
    z = ceiling $ sqrt $ fromIntegral a + 1         -- p'>=z => p'*p'>a
    compositesFrom a = joinT (joinST [multsOf p  a    | p <- h ++ [p']]
                                   : [multsOf p (p*p) | p <- t] )

snapUp v o step = v + (mod (o-v) step)              -- full steps from o
multsOf p from = scanl (\c d->c+p*d) (p*x) wh       -- map (p*) $
  where                                             --   scanl (+) x wh
    (x,wh) = rollFrom (snapUp from p (2*p) `div` p) --   , if p < from 
wheelNums = scanl (+) 0 wheel
rollFrom n = go wheelNums wheel 
  where m = (n-11) `mod` 210  
        go (x:xs) ws@(w:ws') | x < m = go xs ws'
                             | True  = (n+x-m, ws)  -- (x >= m)

A certain preprocessing delay makes it worthwhile when producing more than just a few primes, otherwise it degenerates into simple trial division, which is then ought to be used directly:

primesFrom m = filter isPrime [m..]

Map-based

Runs ~1.7x slower than TME version, but with the same empirical time complexity, ~ (in n primes produced) and same very low (near constant) memory consumption:

import Data.List               -- based on http://stackoverflow.com/a/1140100
import qualified Data.Map as M

primesMPE :: [Integer]
primesMPE = 2:mkPrimes 3 M.empty prs 9   -- postponed addition of primes into map;
  where                                  -- decoupled primes loop feed 
    prs = 3:mkPrimes 5 M.empty prs 9
    mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of
        (False, (n', skips)) | n == n' ->
             mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q
        _ -> if n<q
             then    n : mkPrimes (n+2)  m                  ps q
             else        mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)

    addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m
    addSkips = foldl' . addSkip

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 trial division algorithm:

-- unbounded sieve, premature filters
primesT = sieve [2..]
  where
    sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
  -- map fst . tail 
  --  $ iterate (\(_,p:xs)->(p,[x | x <- xs, rem x p /= 0])) (1,[2..])

This creates many superfluous implicit filters, because they are created prematurely. To be admitted as prime, each number will be tested for divisibility here by all its preceding primes, 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 here is huge.

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 empirically (in n primes produced):

primesToGT m = sieve [2..m]
  where
    sieve (p:xs) 
      | p*p > m = p : xs
      | True    = p : sieve [x | x <- xs, rem x p /= 0]
  -- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail
  --  $ iterate (\(_,p:xs)->(p,[x | x <- xs, rem x p /= 0])) (1,[2..m])

Postponed Filters

Or it can remain unbounded, just filters creation must be postponed until the right moment:

primesPT1 = 2 : sieve primesPT1 [3..] 
  where 
    sieve (p:ps) xs = let (h,t) = span (< p*p) xs 
                      in h ++ sieve ps [x | x<-t, rem x p /= 0]
  -- fix $ (2:) . concat . 
  --   unfoldr (\(xs,p:ps)->let (h,t)=span (< p*p) xs in
  --       Just(h,([x | x <- t, rem x p /= 0],ps))) . ((,) [3..])

This is better re-written with span and (++) inlined and fused into the sieve:

primesPT = 2 : primes'
  where 
    primes' = sieve [3,5..] 9 primes'
    sieve (x:xs) q ps@ ~(p:t)
      | x < q = x : sieve xs q ps
      | True  =     sieve [x | x <- xs, rem x p /= 0] (head t^2) t

creating here as well the linear nested structure at run-time, (...(([3,5..] >>= filterBy [3]) >>= filterBy [5])...), where filterBy ds n = [n | noDivs n ds] (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.

Optimal trial division

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

ps = 2 : [i | i <- [3..],  
              and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]

or,

noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs
-- primes = filter (`noDivs`[2..]) [2..]
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]
isPrime n = n > 1 && noDivs n primesTD

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.

Trial division is used as a simple primality test and prime factorization algorithm.

Segmented Generate and Test

Next we turn the list of filters into one filter by an explicit list, each one in a progression of prefixes of the primes list. This seems to eliminate most recalculations, explicitly filtering composites out from batches of odds between the consecutive squares of primes.

import Data.List

primesST = 2 : oddprimes
  where
    oddprimes = sieve 3 9 oddprimes (inits oddprimes)  -- [],[3],[3,5],...
    sieve x q ~(_:t) (fs:ft) =
      filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]
      ++ sieve (q+2) (head t^2) t ft


Generate and Test Above Limit

The following will start the segmented Turner sieve at the right place, using any primes list it's supplied with (e.g. TMWE etc.) or itself, as shown, demand computing it just up to the square root of any prime it'll produce:

primesFromST m | m > 2 =
    sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)
  where 
    (h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes
    sieve x q ps (fs:ft) =
      filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]
      ++ sieve (q+2) (head ps^2) (tail ps) ft
    oddprimes = 3 : primesFromST 5     -- odd primes

This is usually faster than testing candidate numbers for divisibility one by one which has to re-fetch anew the needed prime factors to test by, for each candidate. Faster is the offset sieve of Eratosthenes on odds, and yet faster the one w/ wheel optimization, on this page.

Conclusions

All these variants being variations of trial division, finding out primes by direct divisibility testing of every candidate 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 principally of worse complexity than that of Sieve of Eratosthenes.

The initial code is just a one-liner that ought to have been regarded as executable specification in the first place. It can easily be improved quite significantly with a simple use of bounded, guarded formulation to limit the number of filters it creates, or by postponement of filter creation.

Euler's Sieve

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:

primesEU = 2 : eulers [3,5..] where
    eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))
 -- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])

This code is extremely inefficient, running above empirical complexity (and worsening rapidly), and should be regarded a specification only. Its memory usage is very high, with empirical space complexity just below , 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, under the simple scheme of producing the multiples by multiplication.

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:

{- fromElt (x,i) = x : fromElt (x + i,i)
                       === iterate  (+ i) x
     [n..]             === fromElt  (n,1) 
                       === fromSpan ([n],1) 
     [n,n+2..]         === fromElt  (n,2)    
                       === fromSpan ([n,n+2],4)     -}

fromSpan (xs,i)  = xs ++ fromSpan (map (+ i) xs,i)

{-                   === concat $ iterate (map (+ i)) xs
   fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i)  
   fromSpan (xs,i) `minus` fromSpan (ys,i) 
                     === fromSpan (xs `minus` ys, i)  
   map (p*) (fromSpan (xs,i)) 
                     === fromSpan (map (p*) xs, p*i)
   fromSpan (xs,i)   === forall (p > 0).
     fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}

spanSpecs = iterate eulerStep ([2],1)
eulerStep (xs@(p:_), i) = 
       ( (tail . concat . take p . iterate (map (+ i))) xs
          `minus` map (p*) xs, p*i )

{- > mapM_ print $ take 4 spanSpecs 
     ([2],1)
     ([3],2)
     ([5,7],6)
     ([7,11,13,17,19,23,29,31],30)  -}

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 are all primes too, so that

eulerPrimesTo m = if m > 1 then go ([2],1) else []
    where
      go w@((p:_), _) 
         | m < p*p = takeWhile (<= m) (fromSpan w)
         | True    = p : go (eulerStep w)

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

Using Immutable Arrays

Generating Segments of Primes

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

import Data.Array.Unboxed
 
primesSA :: [Int]
primesSA = 2 : prs
  where 
    prs = 3 : sieve prs 3 []
    sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] 
                        ++ sieve ps (p*p) ((p,0) : 
                             [(s, rem (y-q) s) | (s,y) <- fs])
     where
      q = (p*p-x)`div`2
      a :: UArray Int Bool
      a = accumArray (\ b c -> False) True (1,q-1)
                     [(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]]

Runs significantly faster than TMWE and with better empirical complexity, of about in producing first few millions of primes, with constant memory footprint.

Calculating Primes Upto a Given Value

Equivalent to Accumulating Array above, running somewhat faster (compiled by GHC with optimizations turned on):

{-# OPTIONS_GHC -O2 #-}
import Data.Array.Unboxed

primesToNA n = 2: [i | i <- [3,5..n], ar ! i]
  where
    ar = f 5 $ accumArray (\ a b -> False) True (3,n) 
                        [(i,()) | i <- [9,15..n]]
    f p a | q > n = a
          | True  = if null x then a' else f (head x) a'
      where q = p*p
            a' :: UArray Int Bool
            a'= a // [(i,False) | i <- [q, q+2*p..n]]
            x = [i | i <- [p+2,p+4..n], a' ! i]

Calculating Primes in a Given Range

primesFromToA a b = (if a<3 then [2] else []) 
                      ++ [i | i <- [o,o+2..b], ar ! i]
  where 
    o  = max (if even a then a+1 else a) 3
    r  = floor . sqrt $ fromIntegral b + 1
    ar = accumArray (\a b-> False) True (o,b) 
          [(i,()) | p <- [3,5..r]
                    , let q  = p*p 
                          s  = 2*p 
                          (n,x) = quotRem (o - q) s 
                          q' = if  o <= q  then q
                               else  q + (n + signum x)*s
                    , i <- [q',q'+s..b] ]

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.

Using Mutable Arrays

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

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.

import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed

sieveUA :: Int -> UArray Int Bool
sieveUA top = runSTUArray $ do
    let m = (top-1) `div` 2
        r = floor . sqrt $ fromIntegral top + 1
    sieve <- newArray (1,m) True      -- :: ST s (STUArray s Int Bool)
    forM_ [1..r `div` 2] $ \i -> do
      isPrime <- readArray sieve i
      when isPrime $ do               -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)
        forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do
          writeArray sieve j False
    return sieve
 
primesToUA :: Int -> [Int]
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]

Its empirical time complexity is improving with n (number of primes produced) from above towards . The reference C++ vector-based implementation exhibits this improvement in empirical time complexity too, from gradually towards , where tested (which might be interpreted as evidence towards the expected quasilinearithmic time complexity).

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.

{-# OPTIONS -O2 -optc-O -XBangPatterns #-}
module Primes (nthPrime) where

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Base
import System
import Control.Monad
import Data.Bits

nthPrime :: Int -> Int
nthPrime n = runST (sieve n)

sieve n = do
    a <- newArray (3,n) True :: ST s (STUArray s Int Bool)
    let cutoff = truncate (sqrt $ fromIntegral n) + 1
    go a n cutoff 3 1

go !a !m cutoff !n !c
    | n >= m    = return c
    | otherwise = do
        e <- unsafeRead a n
        if e then
          if n < cutoff then
            let loop !j
                 | j < m     = do
                        x <- unsafeRead a j
                        when x $ unsafeWrite a j False
                        loop (j+n)
                 | otherwise = go a m cutoff (n+2) (c+1)
            in loop ( if n < 46340 then n * n else n `shiftL` 1)
           else go a m cutoff (n+2) (c+1)
         else go a m cutoff (n+2) c

And place in a module:

{-# OPTIONS -fth #-}
import Primes

main = print $( let x = nthPrime 10000000 in [| x |] )

Run as:

$ ghc --make -o primes Main.hs
$ time ./primes
664579
./primes  0.00s user 0.01s system 228% cpu 0.003 total

Implicit Heap

See Implicit Heap.

Prime Wheels

See Prime Wheels.

Using IntSet for a traditional sieve

See Using IntSet for a traditional sieve.

Testing Primality, and Integer Factorization

See Testing primality:

One-liners

See primes one-liners.

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.