https://wiki.haskell.org/api.php?action=feedcontributions&user=WillNess&feedformat=atomHaskellWiki - User contributions [en]2015-07-30T16:17:56ZUser contributionsMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/Prime_numbersPrime numbers2015-07-19T12:22:32Z<p>WillNess: /* Segmented merging via an array */ style</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (<= n)`, with ordered increasing lists,<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
-- primes = eratos [2.. ] -- unbounded<br />
primesTo m = eratos [2..m] where -- bounded, up to m<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (under (div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
====Segmented merging via an array====<br />
<br />
The removal of composites is easy with arrays. Starting points can be calculated directly:<br />
<br />
<haskell><br />
import Data.List (inits)<br />
import Data.Array.Unboxed<br />
<br />
primesSAE = 2 : sieve 3 4 (tail primesSAE) (inits primesSAE)<br />
where<br />
sieve x q ps (fs:ft) = [i | (i,True) <- assocs (<br />
accumArray (\ _ _ -> False)<br />
True (x,q-1)<br />
[(i,()) | p <- fs, let c = p * div (x+p-1) p,<br />
i <- [c, c+p..q-1]] :: UArray Int Bool )]<br />
++ sieve q (head ps^2) (tail ps) ft<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
The <code>hitsW</code> is there to find the start point for rolling the wheel for each prime, but it can be found directly:<br />
<br />
<haskell><br />
primesW = [2,3,5,7] ++ _Y ( (11:) . tail . gapsW 11 wheel . joinT .<br />
map (\p-> <br />
map (p*) . dropWhile (< p) $<br />
scanl (+) (p - rem (p-11) 210) wheel) ) <br />
</haskell><br />
<br />
Seems to run about 1.4x faster, too.<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-07-19T12:21:29Z<p>WillNess: /* Segmented Tree-merging */ add array-merge subsection</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (<= n)`, with ordered increasing lists,<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
-- primes = eratos [2.. ] -- unbounded<br />
primesTo m = eratos [2..m] where -- bounded, up to m<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (under (div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
====Segmented merging via an array====<br />
<br />
The removal of composites is easy with arrays. Starting points are calculated directly:<br />
<br />
<haskell><br />
import Data.List (inits)<br />
import Data.Array.Unboxed<br />
<br />
primesSAE = 2 : sieve 3 4 (tail primesSAE) (inits primesSAE)<br />
where<br />
sieve x q ps (fs:ft) = [i | (i,True) <- assocs (<br />
accumArray (\ _ _ -> False)<br />
True (x,q-1)<br />
[(i,()) | p <- fs, let c = p * div (x+p-1) p,<br />
i <- [c, c+p..q-1]] :: UArray Int Bool )]<br />
++ sieve q (head ps^2) (tail ps) ft<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
The <code>hitsW</code> is there to find the start point for rolling the wheel for each prime, but it can be found directly:<br />
<br />
<haskell><br />
primesW = [2,3,5,7] ++ _Y ( (11:) . tail . gapsW 11 wheel . joinT .<br />
map (\p-> <br />
map (p*) . dropWhile (< p) $<br />
scanl (+) (p - rem (p-11) 210) wheel) ) <br />
</haskell><br />
<br />
Seems to run about 1.4x faster, too.<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-06-18T16:05:23Z<p>WillNess: /* Tree merging with Wheel */ add another variant</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (<= n)`, with ordered increasing lists,<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
-- primes = eratos [2.. ] -- unbounded<br />
primesTo m = eratos [2..m] where -- bounded, up to m<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (under (div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
The <code>hitsW</code> is there to find the start point for rolling the wheel for each prime, but it can be found directly:<br />
<br />
<haskell><br />
primesW = [2,3,5,7] ++ _Y ( (11:) . tail . gapsW 11 wheel . joinT .<br />
map (\p-> <br />
map (p*) . dropWhile (< p) $<br />
scanl (+) (p - rem (p-11) 210) wheel) ) <br />
</haskell><br />
<br />
Seems to run about 1.4x faster, too.<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-17T17:28:57Z<p>WillNess: /* One-liners */ whitespace</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor . sqrt $ fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
<br />
primes = zipWith (flip (!!)) [0..] . scanl1 minus -- APL-style<br />
. scanl1 (zipWith (+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:t) -> Just . second ((:t) . (`minus` b))<br />
$ span (< head b) a) <br />
. scanl1 (zipWith (+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor . sqrt $ fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
-- producing only unique composites:<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
<br />
primes = 2 : _Y ( (3:) -- unbounded Sieve of Eratosthenes<br />
. minus [5,7..]<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel;<br />
. minus (scanl (+) 13 $ tail wh11) -- 1.4x faster than <br />
. unionAll -- the next one<br />
. map (\p-> map (p*) . dropWhile (< p) $ <br />
scanl (+) (p - rem (p-11) 210) wh11) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) <br />
. minus (scanl (+) 13 $ tail wh11)<br />
. unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> a simpler, duplicates-ignoring variant of <code>union</code>).<br />
<br />
The few last definitions use functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package, and the 2-3-5-7 wheel <code>wh11</code>; they might be leaking space unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-17T17:23:52Z<p>WillNess: /* One-liners */ add comment, tweak code</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
<br />
primes = zipWith (flip (!!)) [0..] . scanl1 minus -- APL-style<br />
. scanl1 (zipWith (+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:t) -> Just . second ((:t) . (`minus` b))<br />
$ span (< head b) a) <br />
. scanl1 (zipWith (+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
-- producing only unique composites:<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
<br />
primes = 2 : _Y ( (3:) -- unbounded Sieve of Eratosthenes<br />
. minus [5,7..]<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel;<br />
. minus (scanl (+) 13 $ tail wh11) -- 1.4x faster than <br />
. unionAll -- the next one<br />
. map (\p-> map (p*) . dropWhile (< p) $ <br />
scanl (+) (p - rem (p-11) 210) wh11) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) <br />
. minus (scanl (+) 13 $ tail wh11)<br />
. unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> a simpler, duplicates-ignoring variant of <code>union</code>).<br />
<br />
The few last definitions use functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package, and the 2-3-5-7 wheel <code>wh11</code>; they might be leaking space unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-17T12:49:17Z<p>WillNess: /* One-liners */ code tweak</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
<br />
primes = 2 : _Y ( (3:) -- unbounded Sieve of Eratosthenes<br />
. minus [5,7..]<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel;<br />
. minus (scanl (+) 13 $ tail wh11) -- 1.4x faster than <br />
. unionAll -- the next one<br />
. map (\p-> map (p*) . dropWhile (< p) . <br />
scanl (+) (p - rem (p-11) 210) $ wh11) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) <br />
. minus (scanl (+) 13 $ tail wh11)<br />
. unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> a simpler, duplicates-ignoring variant of <code>union</code>).<br />
<br />
The few last definitions use functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package, and the 2-3-5-7 wheel <code>wh11</code>; they might be leaking space unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/FoldFold2015-06-17T12:29:58Z<p>WillNess: /* Examples */ c/e</p>
<hr />
<div>In [[functional programming]], ''fold'' (or ''reduce'') is a family of [[higher order function]]s that process a [[data structure]] in some order and build a return value. This is as opposed to the family of ''unfold'' functions which take a starting value and apply it to a function to generate a data structure. <br />
<br />
==Overview==<br />
<br />
Typically, a fold deals with two things: a combining [[Function|function]], and a [[data structure]], typically a [[List (computing)|list]] of elements. The fold then proceeds to combine elements of the data structure using the function in some systematic way. For instance, we might write<br />
<br />
fold (+) [1,2,3,4,5]<br />
<br />
which would result in 1 + 2 + 3 + 4 + 5, which is 15. In this instance, + is an [[associative operation]] so how one parenthesizes the addition is irrelevant to what the final result value will be, although the operational details will differ as to ''how'' it will be calculated. To a rough approximation, you can think of the fold as replacing the commas in the list with the + operation.<br />
<br />
However, in the general case, functions of two parameters are not associative, so the order in which one carries out the combination of the elements matters. On lists, there are two obvious ways to carry this out: either by recursively combining the first element with the results of combining the rest (called a ''right fold'') or by recursively combining the results of combining all but the last element with the last one, (called a ''left fold''). Also, in practice, it is convenient and natural to have an initial value which in the case of a right fold, is used when one reaches the end of the list, and in the case of a left fold, is what is initially combined with the first element of the list. This is perhaps clearer to see in the equations defining <code>foldr</code> and <code>foldl</code> in Haskell. Note that in Haskell, <code>[]</code> represents the empty list, and <code>(x:xs)</code> represents the list starting with x and where the rest of the list is xs.<br />
<haskell><br />
-- if the list is empty, the result is the initial value z; else<br />
-- apply f to the first element and the result of folding the rest<br />
foldr f z [] = z <br />
foldr f z (x:xs) = f x (foldr f z xs) <br />
<br />
-- if the list is empty, the result is the initial value; else<br />
-- we recurse immediately, making the new initial value the result<br />
-- of combining the old initial value with the first element.<br />
foldl f z [] = z <br />
foldl f z (x:xs) = foldl f (f z x) xs <br />
</haskell><br />
One important thing to note in the presence of [[Lazy evaluation | lazy]], or [[Normal-order evaluation | normal-order]] evaluation, is that foldr will immediately return the application of f to the recursive case of folding over the rest of the list. Thus, if f is able to produce some part of its result without reference to the recursive case, and the rest of the result is never demanded, then the recursion will stop. This allows right folds to operate on infinite lists. By contrast, foldl will immediately call itself with new parameters until it reaches the end of the list. This [[tail recursion]] can be efficiently compiled as a loop, but can't deal with infinite lists at all -- it will recurse forever in an [[infinite loop]]. Another technical point to be aware of in the case of left folds in a normal-order evaluation language is that the new initial parameter is not being evaluated before the recursive call is made. This can lead to stack overflows when one reaches the end of the list and tries to evaluate the resulting gigantic expression. For this reason, such languages often provide a stricter variant of left folding which forces the evaluation of the initial parameter before making the recursive call, in Haskell, this is the foldl' (note the apostrophe) function in the Data.List library. Combined with the speed of tail recursion, such folds are very efficient when lazy evaluation of the final result is impossible or undesirable.<br />
<br />
==Special folds for nonempty lists==<br />
<br />
One often wants to choose the [[identity element]] of the operation ''f'' as the initial value ''z''. When no initial value seems appropriate, for example, when one wants to fold the function which computes the maximum of its two parameters over a list in order to get the maximum element of the list, there are variants of foldr and foldl which use the last and first element of the list respectively as the initial value. In Haskell and several other languages, these are called foldr1 and foldl1, the 1 making reference to the automatic provision of an initial element, and the fact that the lists they are applied to must have at least one element.<br />
<br />
These folds use type-symmetrical binary operation: the types of both its arguments, and its result, must be the same. Richard Bird in his 2010 book "Pearls of Functional Algorithm Design" (Cambridge University Press 2010, ISBN 978-0-521-51338-8, p. 42) proposes "a general fold function on non-empty lists" <code>foldrn</code> which transforms its last element, by applying an additional argument function to it, into a value of the result type before starting the folding itself, and is thus able to use type-asymmetrical binary operation like the regular <code>foldr</code> to produce a result of type different from the list's elements type.<br />
<br />
==Tree-like folds==<br />
<br />
The use of initial value is ''mandatory'' when the combining function is ''asymmetrical'' in its types, i.e. when the type of its result is different from the type of list's elements. Then an initial value must be used, with the same type as that of the function's result, for a ''linear'' chain of applications to be possible, whether ''left-'' or ''right-''oriented.<br />
<br />
When the function is ''symmetrical'' in its types the parentheses may be placed in arbitrary fashion thus creating a ''tree'' of nested sub-expressions, e.g. ((1 + 2) + (3 + 4)) + 5. If the binary operation is also ''associative'' this value will be well-defined, i.e. same for any parenthesization, although the operational details of ''how'' it is calculated will differ.<br />
<br />
Both finite and indefinitely defined lists can be folded over in a tree-like fashion (except, the <hask>foldt</hask> below, being recursive, can't work with the infinite lists):<br />
<br />
<br />
<haskell><br />
foldt :: (a -> a -> a) -> a -> [a] -> a<br />
foldt f z [] = z<br />
foldt f z [x] = x<br />
foldt f z xs = foldt f z (pairs f xs)<br />
<br />
foldi :: (a -> a -> a) -> a -> [a] -> a<br />
foldi f z [] = z<br />
foldi f z (x:xs) = f x (foldi f z (pairs f xs))<br />
<br />
pairs :: (a -> a -> a) -> [a] -> [a]<br />
pairs f (x:y:t) = f x y : pairs f t<br />
pairs f t = t<br />
</haskell><br />
<br />
In the case of <code>foldi</code> function, to avoid its runaway evaluation on ''indefinitely'' defined lists the function <code>f</code> must ''not always'' demand its second argument's value, at least not all of it, and/or not immediately (example [[Fold#Examples|below]]).<br />
<br />
==Folds in other languages==<br />
<br />
In Scheme, right and left fold can be written as:<br />
<br />
(define (foldr f z xs)<br />
(if (null? xs)<br />
z<br />
(f (car xs) (foldr f z (cdr xs)))))<br />
<br />
(define (foldl f z xs)<br />
(if (null? xs)<br />
z<br />
(foldl f (f z (car xs)) (cdr xs))))<br />
<br />
The C++ Standard Template Library implements left fold as the function "accumulate" (in the header <numeric>).<br />
<br />
==List folds as structural transformations==<br />
One way in which it is perhaps natural to view folds is as a mechanism for replacing the structural components of a data structure with other functions and values in some regular way. In many languages, lists are built up from two primitives: either the list is the empty list, commonly called ''nil'', or it is a list ''cons''tructed by appending an element to the start of some other list, which we call a ''cons''. In Haskell, the cons operation is written as a colon (:), and in scheme and other lisps, it is called cons. One can view a right fold as ''replacing'' the nil at the end of the list with a specific value, and each cons with a specific other function. Hence, one gets a diagram which looks something like this:<br />
<br />
[[Image:right-fold-transformation.png]]<br />
<br />
In the case of a left fold, the structural transformation being performed is somewhat less natural, but is still quite regular:<br />
<br />
[[Image:left-fold-transformation.png]]<br />
<br />
These pictures do a rather nice job of motivating the names ''left'' and ''right'' fold visually. It also makes obvious the fact that <code>foldr (:) []</code> is the identity function on lists, as replacing cons with cons and nil with nil will not change anything. The left fold diagram suggests an easy way to reverse a list, <hask>foldl (flip (:)) []</hask>. Note that the parameters to cons must be flipped, because the element to add is now the right hand parameter of the combining function. Another easy result to see from this vantage-point is to write the higher-order [[w:Map (higher-order function) | map function]] in terms of foldr, by composing the function to act on the elements with cons, as:<br />
<br />
<haskell><br />
map f = foldr ((:) . f) []<br />
</haskell><br />
where the period (.) is an operator denoting [[function composition]].<br />
<br />
This way of looking at things provides a simple route to designing fold-like functions on other [[Algebraic data type|algebraic data structures]], like various sorts of trees. One writes a function which recursively replaces the constructors of the datatype with provided functions, and any constant values of the type with provided values. Such functions are generally referred to as [[Catamorphisms]].<br />
<br />
==Examples==<br />
<br />
Using a Haskell interpreter, we can show the structural transformation which fold functions perform by constructing a string as follows:<br />
<br />
<source lang="haskell"><br />
Prelude> foldr (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+(12+(13+0)))))))))))))"<br />
<br />
Prelude> foldl (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(((((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)+12)+13)"<br />
<br />
Prelude> foldt (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"((((1+2)+(3+4))+((5+6)+(7+8)))+(((9+10)+(11+12))+13))"<br />
<br />
Prelude> foldi (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(1+((2+3)+(((4+5)+(6+7))+((((8+9)+(10+11))+(12+13))+0))))"<br />
</source><br />
<br />
Infinite tree-like folding is demonstrated e.g. in primes production by unbounded [[Prime_numbers#Tree_merging|sieve of Eratosthenes]]:<br />
<source lang="haskell"><br />
primes :: (Integral a) => [a]<br />
primes = 2 : 3 : ([5,7..] `minus`<br />
foldi (\(x:xs) -> (x:) . union xs) []<br />
[[p*p, p*p+2*p..] | p <- tail primes])<br />
</source><br />
where the function <code>union</code> operates on ordered lists in a local manner to efficiently produce their union, and <code>minus</code> their set difference, defined at [http://hackage.haskell.org/packages/archive/data-ordlist/0.4.4/doc/html/Data-List-Ordered.html#v:minus <code>Data.List.Ordered</code>] package or here at [[Prime numbers#Initial_definition|Prime numbers]] page.<br />
<br />
For finite lists, e.g. merge sort could be easily defined using tree-like folding as<br />
<source lang="haskell"><br />
mergesort :: (Ord a) => [a] -> [a]<br />
mergesort xs = foldt merge [] [[x] | x <- xs]<br />
</source><br />
with the function <code>merge</code> a simpler, duplicates-ignoring variant of <code>union</code>.<br><br />
<br />
Functions <code>head</code> and <code>last</code> could have been defined through folding as<br />
<source lang="haskell"><br />
head = foldr (\a b->a) undefinedâ€‰<br />
last = foldl (\a b->b) undefinedâ€‰<br />
</source><br />
<br />
== See also ==<br />
* [[Foldr Foldl Foldl']]<br />
* [[Foldl as foldr]]<br />
* [[Catamorphisms]]<br />
* [http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29 Wikipedia article on folds]<br />
<br />
==External links==<br />
*[http://www.cse.unsw.edu.au/~en1000/haskell/hof.html "Lists, Map, Fold and Tail Recursion"]<br />
*[http://www.cantab.net/users/antoni.diller/haskell/units/unit06.html "Unit 6: The Higher-order fold Functions"]<br />
<br />
<br />
[[Category:Glossary]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-17T12:09:38Z<p>WillNess: /* One-liners */ correction, c/e; code improvement</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
<br />
primes = 2 : _Y ( (3:) -- unbounded Sieve of Eratosthenes<br />
. minus [5,7..]<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) <br />
. unionAll <br />
. map (\p-> let k = (p-11) `rem` 210 in <br />
map (p*) . dropWhile (< p) . scanl (+) (p-k) $ wh11) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) <br />
. minus (scanl (+) 13 $ tail wh11) <br />
. unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> a simpler, duplicates-ignoring variant of <code>union</code>).<br />
<br />
The few last definitions use functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package, and the 2-3-5-7 wheel <code>wh11</code>; they might be leaking space unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-17T01:56:18Z<p>WillNess: /* One-liners */</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- with wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\p-> let k = p `rem` 210 ;<br />
n = length . takeWhile (< k) <br />
. scanl (+) 11 $ wh11<br />
in map (p*) . scanl (+) p . drop n $ wh11) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) <br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> assumes there are no duplicates).<br />
<br />
The last definition uses functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package and the 2-3-5-7 wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-06-15T23:40:53Z<p>WillNess: /* One-liners */ add 1 more, derived from http://lambda-the-ultimate.org/node/3127#comment-45669</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(p:ps) r-> fix $ ((p*p) :) .<br />
merge r . map (p*) . merge ps) [] $ tails primes)<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> and <code>union</code> of course are on the main page [[Prime_numbers#Initial_definition|here]] (and <code>merge</code> assumes there are no duplicates).<br />
<br />
The last definition uses functions from the [http://hackage.haskell.org/package/data-ordlist <code>data-ordlist</code>] package and the 2-3-5-7 wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-06-01T12:31:58Z<p>WillNess: /* Initial definition */</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (<= n)`, with ordered increasing lists,<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
-- primes = eratos [2.. ] -- unbounded<br />
primesTo m = eratos [2..m] where -- bounded, up to m<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (under (div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-05-25T23:32:39Z<p>WillNess: /* One-liners */ simplify code</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([2,3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-04-30T11:10:30Z<p>WillNess: /* One-liners */ +1</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = fix $ (2:) . concatMap (fst.snd)<br />
. iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0]))<br />
. (, ([3],[4..])) -- (minus xs [p*p,p*p+p..])<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-04-17T00:08:11Z<p>WillNess: /* Sieve of Eratosthenes */ tweak comments</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (<= n)`, with ordered increasing lists,<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (under (div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-04-12T11:44:17Z<p>WillNess: /* One-liners */ reorder, comments, c/e</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1] -- Wilson's theorem<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-04-10T23:04:49Z<p>WillNess: /* Generating Segments of Primes */ code improvement</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (< n)`, with ordered increasing lists<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes ()<br />
where <br />
oddprimes () = 3 : sieve (oddprimes ()) 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/User:WillNessUser:WillNess2015-04-08T11:45:19Z<p>WillNess: </p>
<hr />
<div>I like ''[http://ideone.com/qpnqe this one-liner]'':<br />
<br />
<haskell><br />
-- infinite folding due to Richard Bird<br />
-- double staged primes production due to Melissa O'Neill<br />
-- tree folding idea Heinrich Apfelmus / Dave Bayer <br />
primes = 2 : _Y ((3:) . gaps 5 <br />
. foldi (\(x:xs) -> (x:) . union xs) []<br />
. map (\p-> [p*p, p*p+2*p..])) <br />
<br />
_Y g = g (_Y g) -- multistage production via Y combinator<br />
<br />
gaps k s@(c:t) -- == minus [k,k+2..] (c:t), k<=c,<br />
| k < c = k : gaps (k+2) s -- fused for better performance<br />
| otherwise = gaps (k+2) t -- k==c<br />
</haskell><br />
<br />
<code>foldi</code> is on [[Fold#Tree-like_folds|Tree-like folds]] page. <code>union</code> and more at [[Prime numbers#Sieve_of_Eratosthenes|Prime numbers]].<br />
<br />
The constructive definition of primes is the Sieve of Eratosthenes:<br />
<br />
::::<math>\textstyle\mathbb{S} = \mathbb{N}_{2} \setminus \bigcup_{p\in \mathbb{S}} \{p\,q:q \in \mathbb{N}_{p}\}</math> <br />
using standard definition<br />
::::<math>\textstyle\mathbb{N}_{k} = \{ n \in \mathbb{N} : n \geq k \}</math> &emsp; . . . or, &ensp;<math>\textstyle\mathbb{N}_{k} = \{k\} \bigcup \mathbb{N}_{k+1}</math> .<br />
<br />
Trial division sieve is:<br />
<br />
::::<math>\textstyle\mathbb{T} = \{n \in \mathbb{N}_{2}: (\forall p \in \mathbb{T})(2\leq p\leq \sqrt{n}\, \Rightarrow \neg{(p \mid n)})\}</math><br />
<br />
If you're put off by self-referentiality, just replace <math>\mathbb{S}</math> or <math>\mathbb{T}</math> on the right-hand side of equations with <math>\mathbb{N}_{2}</math>, but even ancient Greeks knew better.</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-04-07T16:12:07Z<p>WillNess: /* One-liners */ add code for Wilson's theorem</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], product [1..n-1] `rem` n == n-1]<br />
<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
The very first definition is based on Wilson's theorem.<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-06T19:39:52Z<p>WillNess: c/e</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element <hask>x</hask> of the list, a function <hask>r</hask> produced by folding over the rest of the list, and the value of an accumulator, <hask>acc</hask>, "from the left". It applies <hask>f</hask> to the accumulator and the list element, and passes the result forward to the function it got "on the right".<br />
<br />
<br />
Because <hask>r</hask> is the same function as constructed by the <hask>construct</hask> here, calling this e.g. for a list <hask>[x,y,...,z]</hask> scans through the whole list as-if evaluating a nested lambda applied to the initial value of the accumulator, <br />
<br />
<br />
<haskell><br />
(\acc-> <br />
(\acc-> <br />
(... (\acc-> (\acc -> acc)<br />
(f acc z)) ...)<br />
(f acc y))<br />
(f acc x)) a<br />
</haskell><br />
<br />
which creates the chain of evaluations as in <br />
<br />
<haskell><br />
(\acc -> acc) (f (... (f (f a x) y) ...) z)<br />
</haskell><br />
<br />
<br />
which is just what the normal <hask>foldl</hask> would do.<br />
<br />
<br />
----<br />
<br />
<br />
The <hask>construct</hask> function could even be made more clever, and inspect the current element in order to decide whether to process the list further or not. Thus, such a variant of <hask>foldl</hask> will be able to stop early, and thus process even infinite lists:<br />
<br />
<br />
<haskell><br />
foldlWhile t f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> if t x then r (f acc x) else acc<br />
</haskell></div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-04-05T14:43:15Z<p>WillNess: /* Sieve of Eratosthenes */ c/e</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
{- Using `under n = takeWhile (< n)`, with ordered increasing lists<br />
`minus` and `_U` satisfy, for any `n`:<br />
under n (minus a b) == under n a \\ under n b<br />
under n (union a b) == nub . sort $ under n a ++ under n b<br />
under n . _U == nub . sort . concat . map (under n) -}<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<code>_U</code> can be defined as a folding of <code>(\(x:xs) -> (x:) . union xs)</code>, or it can use a <code>Bool</code> array as a sorting and duplicates-removing device. The processing naturally divides up into segments between the successive squares of primes.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p,p+p..])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
So for each newly found prime ''p'' 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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes<br />
where <br />
oddprimes = 3 : sieve oddprimes 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-05T00:55:15Z<p>WillNess: style</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element <hask>x</hask> of the list, a function <hask>r</hask> produced by folding over the rest of the list, and the value of an accumulator, <hask>acc</hask>, "from the left". It applies <hask>f</hask> to the accumulator and the list element, and passes the result forward to the function it got "on the right".<br />
<br />
<br />
Because <hask>r</hask> is the same function as constructed by the <hask>construct</hask> here, calling this e.g. for a list <hask>[x,y,...,z]</hask> scans through the whole list creating a nested lambda which is then applied to the initial value of the accumulator, <br />
<br />
<br />
<haskell><br />
(\acc-> <br />
(\acc-> <br />
(... (\acc-> (\acc -> acc)<br />
(f acc z)) ...)<br />
(f acc y))<br />
(f acc x)) a<br />
</haskell><br />
<br />
which, when evaluated, creates the chain of evaluations as in <br />
<br />
<haskell><br />
(\acc -> acc) (f (... (f (f a x) y) ...) z)<br />
</haskell><br />
<br />
<br />
which is just what the normal <hask>foldl</hask> would do.<br />
<br />
<br />
----<br />
<br />
<br />
The <hask>construct</hask> function could even be made more clever, and inspect the current element in order to decide whether to process the list further or not. Thus, such a variant of <hask>foldl</hask> will be able to stop early, and thus process even infinite lists:<br />
<br />
<br />
<haskell><br />
foldlWhile t f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> if t x then r (f acc x) else acc<br />
</haskell></div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-04T22:08:10Z<p>WillNess: finish up - add foldlWhile</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element <hask>x</hask> of the list, a function <hask>r</hask> produced by folding over the rest of the list, and the value of an accumulator, <hask>acc</hask>, "from the left". It applies <hask>f</hask> to the accumulator and the list element, and passes the result forward to the function it got "on the right".<br />
<br />
<br />
Because <hask>r</hask> is the same function as constructed by the <hask>construct</hask> here, calling this e.g. for a list <hask>[x,y,...,z]</hask> scans through the whole list creating a nested lambda which is then applied to the initial value of the accumulator, <br />
<br />
<br />
<haskell><br />
(\acc-> <br />
(\acc-> <br />
(... (\acc-> (\acc -> acc)<br />
(f acc z)) ...)<br />
(f acc y))<br />
(f acc x)) a<br />
</haskell><br />
<br />
which, when evaluated, creates the chain of evaluations as in <br />
<br />
<haskell><br />
(\acc -> acc) (f (... (f (f a x) y) ...) z)<br />
</haskell><br />
<br />
<br />
which is just what the normal <hask>foldl</hask> would do.<br />
<br />
<br />
----<br />
<br />
<br />
The <hask>construct</hask> function could even be made more clever, and inspect the current element in order to decide whether to process the list further or not. Thus, this new variant of <hask>foldl</hask> would be able to stop early, and even process infinite lists:<br />
<br />
<br />
<haskell><br />
foldlWhile t f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> if t x then r (f acc x) else acc<br />
</haskell></div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-04T21:55:02Z<p>WillNess: add example expansion to illustrate</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element <hask>x</hask> of the list, a function <hask>r</hask> produced by folding over the rest of the list, and the value of an accumulator, <hask>acc</hask>, "from the left". It applies <hask>f</hask> to the accumulator and the list element, and passes the result forward to the function it got "on the right".<br />
<br />
Because <hask>r</hask> is the same function as constructed by the <hask>construct</hask> here, calling this for a list <hask>[x,y,...,z]</hask> scans through the whole list creating a nested lambda which is then applied to the initial value of the accumulator, <br />
<br />
<haskell><br />
(\acc-> <br />
(\acc-> <br />
(... (\acc-> (\acc -> acc)<br />
(f acc z)) ...)<br />
(f acc y))<br />
(f acc x)) a<br />
</haskell><br />
<br />
which, when evaluated, creates the chain of evaluations as in <br />
<br />
<haskell><br />
(\acc -> acc) (f (... (f (f a x) y) ...) z)<br />
</haskell><br />
<br />
which is just what the normal <hask>foldl</hask> would do.<br />
<br />
----<br />
<br />
Now, the <hask>construct</hask> function could be more clever, and inspect the current element, in order to decide whether to process the list further or not. Thus, this new variant of <hask>foldl</hask> would be able to stop early.</div>WillNesshttps://wiki.haskell.org/FoldFold2015-04-04T21:39:49Z<p>WillNess: /* Tree-like folds */ correction</p>
<hr />
<div>In [[functional programming]], ''fold'' (or ''reduce'') is a family of [[higher order function]]s that process a [[data structure]] in some order and build a return value. This is as opposed to the family of ''unfold'' functions which take a starting value and apply it to a function to generate a data structure. <br />
<br />
==Overview==<br />
<br />
Typically, a fold deals with two things: a combining [[Function|function]], and a [[data structure]], typically a [[List (computing)|list]] of elements. The fold then proceeds to combine elements of the data structure using the function in some systematic way. For instance, we might write<br />
<br />
fold (+) [1,2,3,4,5]<br />
<br />
which would result in 1 + 2 + 3 + 4 + 5, which is 15. In this instance, + is an [[associative operation]] so how one parenthesizes the addition is irrelevant to what the final result value will be, although the operational details will differ as to ''how'' it will be calculated. To a rough approximation, you can think of the fold as replacing the commas in the list with the + operation.<br />
<br />
However, in the general case, functions of two parameters are not associative, so the order in which one carries out the combination of the elements matters. On lists, there are two obvious ways to carry this out: either by recursively combining the first element with the results of combining the rest (called a ''right fold'') or by recursively combining the results of combining all but the last element with the last one, (called a ''left fold''). Also, in practice, it is convenient and natural to have an initial value which in the case of a right fold, is used when one reaches the end of the list, and in the case of a left fold, is what is initially combined with the first element of the list. This is perhaps clearer to see in the equations defining <code>foldr</code> and <code>foldl</code> in Haskell. Note that in Haskell, <code>[]</code> represents the empty list, and <code>(x:xs)</code> represents the list starting with x and where the rest of the list is xs.<br />
<haskell><br />
-- if the list is empty, the result is the initial value z; else<br />
-- apply f to the first element and the result of folding the rest<br />
foldr f z [] = z <br />
foldr f z (x:xs) = f x (foldr f z xs) <br />
<br />
-- if the list is empty, the result is the initial value; else<br />
-- we recurse immediately, making the new initial value the result<br />
-- of combining the old initial value with the first element.<br />
foldl f z [] = z <br />
foldl f z (x:xs) = foldl f (f z x) xs <br />
</haskell><br />
One important thing to note in the presence of [[Lazy evaluation | lazy]], or [[Normal-order evaluation | normal-order]] evaluation, is that foldr will immediately return the application of f to the recursive case of folding over the rest of the list. Thus, if f is able to produce some part of its result without reference to the recursive case, and the rest of the result is never demanded, then the recursion will stop. This allows right folds to operate on infinite lists. By contrast, foldl will immediately call itself with new parameters until it reaches the end of the list. This [[tail recursion]] can be efficiently compiled as a loop, but can't deal with infinite lists at all -- it will recurse forever in an [[infinite loop]]. Another technical point to be aware of in the case of left folds in a normal-order evaluation language is that the new initial parameter is not being evaluated before the recursive call is made. This can lead to stack overflows when one reaches the end of the list and tries to evaluate the resulting gigantic expression. For this reason, such languages often provide a stricter variant of left folding which forces the evaluation of the initial parameter before making the recursive call, in Haskell, this is the foldl' (note the apostrophe) function in the Data.List library. Combined with the speed of tail recursion, such folds are very efficient when lazy evaluation of the final result is impossible or undesirable.<br />
<br />
==Special folds for nonempty lists==<br />
<br />
One often wants to choose the [[identity element]] of the operation ''f'' as the initial value ''z''. When no initial value seems appropriate, for example, when one wants to fold the function which computes the maximum of its two parameters over a list in order to get the maximum element of the list, there are variants of foldr and foldl which use the last and first element of the list respectively as the initial value. In Haskell and several other languages, these are called foldr1 and foldl1, the 1 making reference to the automatic provision of an initial element, and the fact that the lists they are applied to must have at least one element.<br />
<br />
These folds use type-symmetrical binary operation: the types of both its arguments, and its result, must be the same. Richard Bird in his 2010 book "Pearls of Functional Algorithm Design" (Cambridge University Press 2010, ISBN 978-0-521-51338-8, p. 42) proposes "a general fold function on non-empty lists" <code>foldrn</code> which transforms its last element, by applying an additional argument function to it, into a value of the result type before starting the folding itself, and is thus able to use type-asymmetrical binary operation like the regular <code>foldr</code> to produce a result of type different from the list's elements type.<br />
<br />
==Tree-like folds==<br />
<br />
The use of initial value is ''mandatory'' when the combining function is ''asymmetrical'' in its types, i.e. when the type of its result is different from the type of list's elements. Then an initial value must be used, with the same type as that of the function's result, for a ''linear'' chain of applications to be possible, whether ''left-'' or ''right-''oriented.<br />
<br />
When the function is ''symmetrical'' in its types the parentheses may be placed in arbitrary fashion thus creating a ''tree'' of nested sub-expressions, e.g. ((1 + 2) + (3 + 4)) + 5. If the binary operation is also ''associative'' this value will be well-defined, i.e. same for any parenthesization, although the operational details of ''how'' it is calculated will differ.<br />
<br />
Both finite and indefinitely defined lists can be folded over in a tree-like fashion (except, the <hask>foldt</hask> below, being recursive, can't work with the infinite lists):<br />
<br />
<br />
<haskell><br />
foldt :: (a -> a -> a) -> a -> [a] -> a<br />
foldt f z [] = z<br />
foldt f z [x] = x<br />
foldt f z xs = foldt f z (pairs f xs)<br />
<br />
foldi :: (a -> a -> a) -> a -> [a] -> a<br />
foldi f z [] = z<br />
foldi f z (x:xs) = f x (foldi f z (pairs f xs))<br />
<br />
pairs :: (a -> a -> a) -> [a] -> [a]<br />
pairs f (x:y:t) = f x y : pairs f t<br />
pairs f t = t<br />
</haskell><br />
<br />
In the case of <code>foldi</code> function, to avoid its runaway evaluation on ''indefinitely'' defined lists the function <code>f</code> must ''not always'' demand its second argument's value, at least not all of it, and/or not immediately (example [[Fold#Examples|below]]).<br />
<br />
==Folds in other languages==<br />
<br />
In Scheme, right and left fold can be written as:<br />
<br />
(define (foldr f z xs)<br />
(if (null? xs)<br />
z<br />
(f (car xs) (foldr f z (cdr xs)))))<br />
<br />
(define (foldl f z xs)<br />
(if (null? xs)<br />
z<br />
(foldl f (f z (car xs)) (cdr xs))))<br />
<br />
The C++ Standard Template Library implements left fold as the function "accumulate" (in the header <numeric>).<br />
<br />
==List folds as structural transformations==<br />
One way in which it is perhaps natural to view folds is as a mechanism for replacing the structural components of a data structure with other functions and values in some regular way. In many languages, lists are built up from two primitives: either the list is the empty list, commonly called ''nil'', or it is a list ''cons''tructed by appending an element to the start of some other list, which we call a ''cons''. In Haskell, the cons operation is written as a colon (:), and in scheme and other lisps, it is called cons. One can view a right fold as ''replacing'' the nil at the end of the list with a specific value, and each cons with a specific other function. Hence, one gets a diagram which looks something like this:<br />
<br />
[[Image:right-fold-transformation.png]]<br />
<br />
In the case of a left fold, the structural transformation being performed is somewhat less natural, but is still quite regular:<br />
<br />
[[Image:left-fold-transformation.png]]<br />
<br />
These pictures do a rather nice job of motivating the names ''left'' and ''right'' fold visually. It also makes obvious the fact that <code>foldr (:) []</code> is the identity function on lists, as replacing cons with cons and nil with nil will not change anything. The left fold diagram suggests an easy way to reverse a list, <hask>foldl (flip (:)) []</hask>. Note that the parameters to cons must be flipped, because the element to add is now the right hand parameter of the combining function. Another easy result to see from this vantage-point is to write the higher-order [[w:Map (higher-order function) | map function]] in terms of foldr, by composing the function to act on the elements with cons, as:<br />
<br />
<haskell><br />
map f = foldr ((:) . f) []<br />
</haskell><br />
where the period (.) is an operator denoting [[function composition]].<br />
<br />
This way of looking at things provides a simple route to designing fold-like functions on other [[Algebraic data type|algebraic data structures]], like various sorts of trees. One writes a function which recursively replaces the constructors of the datatype with provided functions, and any constant values of the type with provided values. Such functions are generally referred to as [[Catamorphisms]].<br />
<br />
==Examples==<br />
<br />
Using a Haskell interpreter, we can show the structural transformation which fold functions perform by constructing a string as follows:<br />
<br />
<source lang="haskell"><br />
Prelude> foldr (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+(11+(12+(13+0)))))))))))))"<br />
<br />
Prelude> foldl (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(((((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)+11)+12)+13)"<br />
<br />
Prelude> foldt (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"((((1+2)+(3+4))+((5+6)+(7+8)))+(((9+10)+(11+12))+13))"<br />
<br />
Prelude> foldi (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..13])<br />
"(1+((2+3)+(((4+5)+(6+7))+((((8+9)+(10+11))+(12+13))+0))))"<br />
</source><br />
<br />
Infinite tree-like folding is demonstrated e.g. in primes production by unbounded [[Prime_numbers#Tree_merging|sieve of Eratosthenes]]:<br />
<source lang="haskell"><br />
primes :: (Integral a) => [a]<br />
primes = 2 : 3 : ([5,7..] `minus`<br />
foldi (\(x:xs) -> (x:) . union xs) []<br />
[[p*p, p*p+2*p..] | p <- tail primes])<br />
</source><br />
where the function <code>union</code> operates on ordered lists in a local manner to efficiently produce their union, and <code>minus</code> their set difference, defined at [http://hackage.haskell.org/packages/archive/data-ordlist/0.4.4/doc/html/Data-List-Ordered.html#v:minus <code>Data.List.Ordered</code>] package or here at [[Prime numbers#Initial_definition|Prime numbers]] page.<br />
<br />
For finite lists, e.g. merge sort could be easily defined using tree-like folding as<br />
<source lang="haskell"><br />
mergesort :: (Ord a) => [a] -> [a]<br />
mergesort xs = foldt merge [] [[x] | x <- xs]<br />
</source><br />
with the function <code>merge</code> a duplicates-preserving variant of <code>union</code>.<br><br />
<br />
Functions <code>head</code> and <code>last</code> could have been defined through folding as<br />
<source lang="haskell"><br />
head = foldr (\a b->a) undefinedâ€‰<br />
last = foldl (\a b->b) undefinedâ€‰<br />
</source><br />
<br />
== See also ==<br />
* [[Foldr Foldl Foldl']]<br />
* [[Foldl as foldr]]<br />
* [[Catamorphisms]]<br />
* [http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29 Wikipedia article on folds]<br />
<br />
==External links==<br />
*[http://www.cse.unsw.edu.au/~en1000/haskell/hof.html "Lists, Map, Fold and Tail Recursion"]<br />
*[http://www.cantab.net/users/antoni.diller/haskell/units/unit06.html "Unit 6: The Higher-order fold Functions"]<br />
<br />
<br />
[[Category:Glossary]]</div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-04T13:56:45Z<p>WillNess: c/e</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element <hask>x</hask> of the list, a function <hask>r</hask> produced by folding over the rest of the list, and the value of an accumulator, <hask>acc</hask>, "from the left". It applies <hask>f</hask> to the accumulator and the list element, and passes the result forward to the function it got "on the right".</div>WillNesshttps://wiki.haskell.org/Foldl_as_foldr_alternativeFoldl as foldr alternative2015-04-04T13:31:46Z<p>WillNess: rename a function, comments, c/e to clarify; add link</p>
<hr />
<div>This page explains how <hask>foldl</hask> can be written using <hask>foldr</hask>. Yes, there is already [[Foldl as foldr|such a page]]! This one explains it differently.<br />
<br />
<br />
The usual definition of <hask>foldl</hask> looks like this:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a [] = a<br />
foldl f a (x : xs) = foldl f (f a x) xs<br />
</haskell><br />
<br />
<br />
Now the <hask>f</hask> never changes in the recursion. It turns out things will be simpler later if we pull it out:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go a list<br />
where<br />
go acc [] = acc<br />
go acc (x : xs) = go (f acc x) xs<br />
</haskell><br />
<br />
<br />
-----<br />
<br />
<br />
For some reason (maybe we're crazy; maybe we want to do weird things with fusion; who knows?) we want to write this using <hask>foldr</hask>. Haskell programmers like curry, so it's natural to see <hask>go acc xs</hask> as <hask>(go acc) xs</hask>&mdash;that is, to see <hask>go a</hask> as a function that takes a list and returns the result of folding <hask>f</hask> into the list starting with an accumulator value of <hask>a</hask>. This perspective, however, is the ''wrong one'' for what we're trying to do here. So let's change the order of the arguments of the helper:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] acc = acc<br />
go2 (x : xs) acc = go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
So now we see that <hask>go2 xs</hask> is a function that takes an accumulator and uses it as the initial value to fold <hask>f</hask> into <hask>xs</hask>. With this shift of perspective, we can rewrite <hask>go2</hask> just a little, shifting its second argument into an explicit lambda:<br />
<br />
<br />
<haskell><br />
foldl :: (a -> x -> r) -> a -> [x] -> r<br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = \acc -> acc<br />
go2 (x : xs) = \acc -> go2 xs (f acc x)<br />
</haskell><br />
<br />
<br />
Believe it or not, we're almost done! How is that? Let's parenthesize a bit for emphasis:<br />
<br />
<br />
<haskell><br />
foldl f a list = go2 list a<br />
where<br />
go2 [] = (\acc -> acc) -- nil case<br />
go2 (x : xs) = \acc -> (go2 xs) (f acc x) -- construct x (go2 xs)<br />
</haskell><br />
<br />
<br />
This isn't an academic paper, so we won't mention Graham Hutton's [https://www.cs.nott.ac.uk/~gmh/fold.pdf "Tutorial on the Universality and Expressiveness of Fold"], but <hask>go2</hask> fits the <hask>foldr</hask> pattern, constructing its result in non-nil case from the list's head element (<hask>x</hask>) and the recursive result for its tail (<hask>go2 xs</hask>):<br />
<br />
<br />
<haskell><br />
go2 list = foldr construct (\acc -> acc) list<br />
where<br />
construct x r = \acc -> r (f acc x) <br />
</haskell><br />
<br />
<br />
Substituting this in,<br />
<br />
<br />
<haskell><br />
foldl f a list = (foldr construct (\acc -> acc) list) a<br />
where<br />
construct x r = \acc -> r (f acc x)<br />
</haskell><br />
<br />
<br />
And that's all she wrote! One way to look at this final expression is that <hask>construct</hask> takes an element of the list, a function produced by folding over the rest of the list, and the value of an accumulator. It applies <hask>f</hask> to the accumulator it's given and the list element, and passes the result forward to the function it got.</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-03-01T10:16:09Z<p>WillNess: /* Tree merging */ ws</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes<br />
where <br />
oddprimes = 3 : sieve oddprimes 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-03-01T10:13:48Z<p>WillNess: /* One-liners */ comment about space leak and the fix for it.</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>. The last two definitions are leaking space, unless <code>minus</code> is fused with its input (into [[Prime_numbers#Tree merging |<code>gaps</code>]]/[[Prime_numbers#Tree merging with Wheel|<code>gapsW</code>]] from the main page).<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-02-27T00:06:06Z<p>WillNess: /* Linear merging */ fit the code width</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) <br />
[] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes<br />
where <br />
oddprimes = 3 : sieve oddprimes 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-02-26T23:42:24Z<p>WillNess: /* One-liners */ fit to width in IE, add wheeled one-liner using data-ordlist functions</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], <br />
k<-[2..min j (n`div`j)]]]<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) <br />
[3,5..floor.sqrt$fromIntegral n]]<br />
primes = zipWith (flip (!!)) [0..] -- APL-style<br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] <br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0 && r))<br />
True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..], foldr (\p r-> p*p>n || (rem n p>0<br />
&& r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],<br />
tail primes))<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } <br />
in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] -- ~= unionAll<br />
. map (\p->[p*p, p*p+2*p..]) )<br />
primes = [2,3,5,7] ++ _Y ( (11:) -- using a wheel<br />
. minus (scanl (+) 13 $ tail wh11) . unionAll<br />
. map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w)<br />
. isectBy (compare . snd)<br />
(tails wh11 `zip` scanl (+) 11 wh11) ) <br />
_Y g = g (_Y g)<br />
wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: <br />
4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
The last definition uses functions from the <code>data-ordlist</code> package and the 2-3-5-7-wheel <code>wh11</code>.<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-02-07T16:12:46Z<p>WillNess: /* One-liners */ on more</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..min j (n`div`j)]]]<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) [3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = zipWith (flip (!!)) [0..] <br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] -- APL-style<br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = nub $ map head $ scanl (\xs x-> filter ((> 0).(`rem`x)) xs) [2..] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],tail primes))<br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] <br />
. map (\p->[p*p, p*p+2*p..]) )<br />
_Y g = g (_Y g)<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-02-03T12:06:27Z<p>WillNess: /* One-liners */</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..min j (n`div`j)]]]<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) [3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = zipWith (flip (!!)) [0..] <br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] -- APL-style<br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, ((`minus` [p*p, p*p+2*p..]) t, ps))) ([5,7..],tail primes))<br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] <br />
. map (\p->[p*p, p*p+2*p..]) )<br />
_Y g = g (_Y g)<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-02-01T20:11:54Z<p>WillNess: /* One-liners */ add one more</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..min j (n`div`j)]]]<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) [3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = zipWith (flip (!!)) [0..] <br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] -- APL-style<br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True xs])<br />
<br />
primes = foldr (\x xs-> x : filter ((> 0).(`rem`x)) xs) [] [2..]<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (t `minus` [p*p, p*p+2*p..], ps))) ([5,7..],tail primes))<br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] <br />
. map (\p->[p*p, p*p+2*p..]) )<br />
_Y g = g (_Y g)<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-01-26T12:00:40Z<p>WillNess: /* Prime Wheels */ remove apostrophes in names; c/e</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:prs<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
prs = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) prs<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>prs</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r2 | k <- [0..(p-1)], r <- rs,<br />
let r2 = n*k+r, r2 `mod` p /= 0]<br />
</haskell><br />
<br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but adapting the wheel size while generating prime numbers quickly becomes impractical, because the circumference grows very fast, as primorial, but the returns quickly diminish, the improvement being just <code>(p-1)/p</code>. See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..min j (n`div`j)]]]<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) [3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = zipWith (flip (!!)) [0..] <br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] -- APL-style<br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True xs])<br />
<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (t `minus` [p*p, p*p+2*p..], ps))) ([5,7..],tail primes))<br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] <br />
. map (\p->[p*p, p*p+2*p..]) )<br />
_Y g = g (_Y g)<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-01-26T11:37:12Z<p>WillNess: /* Using Immutable Arrays */ get rid of apostrophes in var names</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : oddprimes<br />
where <br />
oddprimes = 3 : sieve oddprimes 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a2 else f (head x) a2<br />
where q = p*p<br />
a2 :: UArray Int Bool<br />
a2 = a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a2 ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q2 = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q2,q2+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-01-26T11:33:10Z<p>WillNess: /* Postponed Filters */ rename apostrophed vars</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : prs<br />
where <br />
prs = 3 : sieve prs 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a' else f (head x) a'<br />
where q = p*p<br />
a' :: UArray Int Bool<br />
a'= a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a' ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q' = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q',q'+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2015-01-26T11:20:36Z<p>WillNess: /* Sieve of Eratosthenes */ rename apostrophes in names - bad highlighting</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : oddprimes<br />
where <br />
oddprimes = sieve [3,5..] 9 oddprimes<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : oddprimes<br />
where <br />
oddprimes = sieve 3 9 oddprimes []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : prs where<br />
prs = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- prs])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh2 (compositesFrom a)<br />
where<br />
(a,wh2) = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p2:t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p2>=z => p2*p2>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p2]]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws2) | x < m = go xs ws2<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n2, skips)) | n == n2 -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : primes'<br />
where <br />
primes' = sieve [3,5..] 9 primes'<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : prs<br />
where <br />
prs = 3 : sieve prs 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a' else f (head x) a'<br />
where q = p*p<br />
a' :: UArray Int Bool<br />
a'= a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a' ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q' = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q',q'+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./primes 0.00s user 0.01s system 228% cpu 0.003 total<br />
</haskell><br />
<br />
== Implicit Heap ==<br />
<br />
See [[Prime_numbers_miscellaneous#Implicit_Heap | Implicit Heap]].<br />
<br />
== Prime Wheels ==<br />
<br />
See [[Prime_numbers_miscellaneous#Prime_Wheels | Prime Wheels]].<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<br />
See [[Prime_numbers_miscellaneous#Using_IntSet_for_a_traditional_sieve | Using IntSet for a traditional sieve]].<br />
<br />
== Testing Primality, and Integer Factorization ==<br />
<br />
See [[Testing_primality | Testing primality]]:<br />
<br />
* [[Testing_primality#Primality_Test_and_Integer_Factorization | Primality Test and Integer Factorization ]]<br />
* [[Testing_primality#Miller-Rabin_Primality_Test | Miller-Rabin Primality Test]]<br />
<br />
== One-liners ==<br />
See [[Prime_numbers_miscellaneous#One-liners | primes one-liners]].<br />
<br />
== External links ==<br />
* http://www.cs.hmc.edu/~oneill/code/haskell-primes.zip<br />
: A collection of prime generators; the file "ONeillPrimes.hs" contains one of the fastest pure-Haskell prime generators; code by Melissa O'Neill. <br />
: 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.<br />
<br />
* [http://ideone.com/willness/primes test entries] for (some of) the above code variants.<br />
<br />
* Speed/memory [http://ideone.com/p0e81 comparison table] for sieve of Eratosthenes variants.<br />
<br />
[[Category:Code]]<br />
[[Category:Mathematics]]</div>WillNesshttps://wiki.haskell.org/Prime_numbers_miscellaneousPrime numbers miscellaneous2015-01-08T11:27:42Z<p>WillNess: /* One-liners */ simplify</p>
<hr />
<div>For a context to this, please see [[Prime numbers#Implicit_Heap | Prime numbers]].<br />
<br />
== Implicit Heap ==<br />
<br />
The following is an original implicit heap implementation for the sieve of<br />
Eratosthenes, kept here for historical record. Also, it implements more sophisticated, lazier scheduling. The [[Prime_numbers#Tree merging with Wheel]] section simplifies it, removing the <code>People a</code> structure altogether, and improves upon it by using a folding tree structure better adjusted for primes processing, and a [[Prime_numbers#Euler.27s_Sieve | wheel]] optimization.<br />
<br />
See also the message threads [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/25270/focus=25312 Re: "no-coding" functional data structures via lazyness] for more about how merging ordered lists amounts to creating an implicit heap and [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/26426/focus=26493 Re: Code and Perf. Data for Prime Finders] for an explanation of the <code>People a</code> structure that makes it work.<br />
<br />
<haskell><br />
data People a = VIP a (People a) | Crowd [a]<br />
<br />
mergeP :: Ord a => People a -> People a -> People a<br />
mergeP (VIP x xt) ys = VIP x $ mergeP xt ys<br />
mergeP (Crowd xs) (Crowd ys) = Crowd $ merge xs ys<br />
mergeP xs@(Crowd (x:xt)) ys@(VIP y yt) = case compare x y of<br />
LT -> VIP x $ mergeP (Crowd xt) ys<br />
EQ -> VIP x $ mergeP (Crowd xt) yt<br />
GT -> VIP y $ mergeP xs yt<br />
<br />
merge :: Ord a => [a] -> [a] -> [a]<br />
merge xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : merge xt ys<br />
EQ -> x : merge xt yt<br />
GT -> y : merge xs yt<br />
<br />
diff xs@(x:xt) ys@(y:yt) = case compare x y of<br />
LT -> x : diff xt ys<br />
EQ -> diff xt yt<br />
GT -> diff xs yt<br />
<br />
foldTree :: (a -> a -> a) -> [a] -> a<br />
foldTree f ~(x:xs) = x `f` foldTree f (pairs xs)<br />
where pairs ~(x: ~(y:ys)) = f x y : pairs ys<br />
<br />
primes, nonprimes :: [Integer]<br />
primes = 2:3:diff [5,7..] nonprimes<br />
nonprimes = serve . foldTree mergeP . map multiples $ tail primes<br />
where<br />
multiples p = vip [p*p,p*p+2*p..]<br />
<br />
vip (x:xs) = VIP x $ Crowd xs<br />
serve (VIP x xs) = x:serve xs<br />
serve (Crowd xs) = xs<br />
</haskell><br />
<br />
<code>nonprimes</code> effectively implements a heap, exploiting lazy evaluation.<br />
<br />
== Prime Wheels ==<br />
<br />
The idea of only testing odd numbers can be extended further. For instance, it is a useful fact that every prime number other than 2 and 3 must be of the form <math>6k+1</math> or <math>6k+5</math>. Thus, we only need to test these numbers:<br />
<br />
<haskell><br />
primes :: [Integer]<br />
primes = 2:3:primes'<br />
where<br />
1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]<br />
primes' = p : filter isPrime candidates<br />
isPrime n = all (not . divides n)<br />
$ takeWhile (\p -> p*p <= n) primes'<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
<br />
Here, <hask>primes'</hask> is the list of primes greater than 3 and <hask>isPrime</hask> does not test for divisibility by 2 or 3 because the <hask>candidates</hask> by construction don't have these numbers as factors. We also need to exclude 1 from the candidates and mark the next one as prime to start the recursion.<br />
<br />
Such a scheme to generate candidate numbers first that avoid a given set of primes as divisors is called a '''prime wheel'''. Imagine that you had a wheel of circumference 6 to be rolled along the number line. With spikes positioned 1 and 5 units around the circumference, rolling the wheel will prick holes exactly in those positions on the line whose numbers are not divisible by 2 and 3.<br />
<br />
A wheel can be represented by its circumference and the spiked positions.<br />
<haskell><br />
data Wheel = Wheel Integer [Integer]<br />
</haskell><br />
We prick out numbers by rolling the wheel.<br />
<haskell><br />
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]<br />
</haskell><br />
The smallest wheel is the unit wheel with one spike, it will prick out every number.<br />
<haskell><br />
w0 = Wheel 1 [1]<br />
</haskell><br />
We can create a larger wheel by rolling a smaller wheel of circumference <hask>n</hask> along a rim of circumference <hask>p*n</hask> while excluding spike positions at multiples of <hask>p</hask>.<br />
<haskell><br />
nextSize (Wheel n rs) p =<br />
Wheel (p*n) [r' | k <- [0..(p-1)], r <- rs,<br />
let r' = n*k+r, r' `mod` p /= 0]<br />
</haskell><br />
Combining both, we can make wheels that prick out numbers that avoid a given list <hask>ds</hask> of divisors.<br />
<haskell><br />
mkWheel ds = foldl nextSize w0 ds<br />
</haskell><br />
<br />
Now, we can generate prime numbers with a wheel that for instance avoids all multiples of 2, 3, 5 and 7.<br />
<haskell><br />
primes :: [Integer]<br />
primes = small ++ large<br />
where<br />
1:p:candidates = roll $ mkWheel small<br />
small = [2,3,5,7]<br />
large = p : filter isPrime candidates<br />
isPrime n = all (not . divides n) <br />
$ takeWhile (\p -> p*p <= n) large<br />
divides n p = n `mod` p == 0<br />
</haskell><br />
It's a pretty big wheel with a circumference of 210 and allows us to calculate the first 10000 primes in convenient time.<br />
<br />
A fixed size wheel is fine, but how about adapting the wheel size while generating prime numbers? See [[Prime_numbers#Euler.27s_Sieve | Euler's Sieve]], or the [[Research papers/Functional pearls|functional pearl]] titled [http://citeseer.ist.psu.edu/runciman97lazy.html Lazy wheel sieves and spirals of primes] for more.<br />
<br />
== Using IntSet for a traditional sieve ==<br />
<haskell><br />
<br />
module Sieve where<br />
import qualified Data.IntSet as I<br />
<br />
-- findNext - finds the next member of an IntSet.<br />
findNext c is | I.member c is = c<br />
| c > I.findMax is = error "Ooops. No next number in set."<br />
| otherwise = findNext (c+1) is<br />
<br />
-- mark - delete all multiples of n from n*n to the end of the set<br />
mark n is = is I.\\ (I.fromAscList (takeWhile (<=end) (map (n*) [n..])))<br />
where<br />
end = I.findMax is<br />
<br />
-- primes - gives all primes up to n <br />
primes n = worker 2 (I.fromAscList [2..n])<br />
where<br />
worker x is <br />
| (x*x) > n = is<br />
| otherwise = worker (findNext (x+1) is) (mark x is)<br />
</haskell><br />
<br />
''(doesn't look like it runs very efficiently)''.<br />
<br />
<br />
<br />
== One-liners ==<br />
<br />
<haskell>primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..n-1]]]<br />
primes = [n | n<-[2..], not $ elem n [j*k | j<-[2..n-1], k<-[2..min j (n`div`j)]]]<br />
<br />
primes = nubBy (((>1).).gcd) [2..]<br />
primes = [n | n<-[2..], all ((> 0).rem n) [2..n-1]]<br />
primes = 2 : [n | n<-[3,5..], all ((> 0).rem n) [3,5..floor.sqrt$fromIntegral n]]<br />
<br />
primes = zipWith (flip (!!)) [0..] <br />
. scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] -- APL-style<br />
primes = tail . concat . unfoldr (\(a:b:r)-> let (h,t)=span (< head b) a in<br />
Just (h, minus t b : r)) . scanl1 (zipWith(+) . tail) $ tails [1..]<br />
<br />
primes = 2 : [n | n<-[3..], all ((> 0).rem n) $ takeWhile ((<= n).(^2)) primes]<br />
primes = 2 : 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True $ tail primes]<br />
primes = 2 : fix (\xs-> 3 : [n | n<-[5,7..],<br />
foldr (\p r-> p*p>n || (rem n p>0 && r)) True xs])<br />
<br />
primes = map head $ iterate (\(x:xs)-> filter ((> 0).(`rem`x)) xs) [2..]<br />
primes = 2 : unfoldr (\(x:xs)-> Just(x, filter ((> 0).(`rem`x)) xs)) [3,5..]<br />
<br />
primesTo n = foldl (\r x-> r `minus` [x*x, x*x+2*x..]) (2:[3,5..n]) <br />
[3,5..floor.sqrt$fromIntegral n]<br />
primesTo n = 2 : foldr (\r z-> if (head r^2) <= n then head r : z else r) [] <br />
(iterate (\(p:t)-> minus t [p*p, p*p+2*p..]) [3,5..n])<br />
<br />
primes = 2 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (filter ((> 0).(`rem`p)) t, ps))) ([3,5..],[3,5..]))<br />
primes = 2 : 3 : concat (unfoldr (\(xs,p:ps)-> let (h,t)=span (< p*p) xs in <br />
Just (h, (t `minus` [p*p, p*p+2*p..], ps))) ([5,7..],tail primes))<br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), [x | x <- [x, x+2 .. p*p-2],<br />
all ((/= 0).rem x) fs])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = 2 : _Y (\ps-> concatMap snd $ iterate (\((fs:ft, x, p:t),_) -> <br />
((ft,p*p+2,t), minus [x, x+2 .. p*p-2] <br />
$ foldi union [] [[o, o+2*i .. p*p-2] | i <- fs, <br />
let o=x+mod(i-x)(2*i)])) ((inits ps, 5, ps), [3]) ) <br />
<br />
primes = let { sieve (x:xs) = x : sieve [n | n <- xs, rem n x > 0] } in sieve [2..] <br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (filter ((> 0).(`rem`p)) t) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
primes = let { sieve xs (p:ps) = let (h,t)=span (< p*p) xs in <br />
h ++ sieve (t `minus` [p*p, p*p+2*p..]) ps } <br />
in 2 : 3 : sieve [5,7..] (tail primes)<br />
<br />
primes = 2 : minus [3..] (foldr (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+x..]) primes)<br />
primes = 2 : minus [3,5..] (foldi (\(x:xs)->(x:).union xs) [] <br />
$ map (\x->[x*x, x*x+2*x..]) [3,5..])<br />
primes = 2 : _Y ( (3:) . minus [5,7..] -- unbounded Sieve of Eratosthenes<br />
. foldi (\(x:xs) ys-> x:union xs ys) [] <br />
. map (\p->[p*p, p*p+2*p..]) )<br />
_Y g = g (_Y g)<br />
</haskell><br />
<br />
<code>foldi</code> is an infinitely right-deepening tree folding function found [[Fold#Tree-like_folds|here]]. <code>minus</code> of course is on the main page [[Prime_numbers#Initial_definition|here]].<br />
<br />
[[Category:Code]]</div>WillNesshttps://wiki.haskell.org/Prime_numbersPrime numbers2014-11-18T10:11:07Z<p>WillNess: /* Sieve of Eratosthenes */ +code comments</p>
<hr />
<div>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).<br />
<br />
== Prime Number Resources ==<br />
<br />
* At Wikipedia:<br />
**[http://en.wikipedia.org/wiki/Prime_numbers Prime Numbers]<br />
**[http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Sieve of Eratosthenes]<br />
<br />
* HackageDB packages:<br />
** [http://hackage.haskell.org/package/arithmoi arithmoi]: Various basic number theoretic functions; efficient array-based sieves, Montgomery curve factorization ...<br />
** [http://hackage.haskell.org/package/Numbers Numbers]: An assortment of number theoretic functions.<br />
** [http://hackage.haskell.org/package/NumberSieves NumberSieves]: Number Theoretic Sieves: primes, factorization, and Euler's Totient.<br />
** [http://hackage.haskell.org/package/primes primes]: Efficient, purely functional generation of prime numbers.<br />
<br />
* Papers:<br />
** 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.<br />
<br />
== Definition ==<br />
<br />
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<br />
<br />
: &nbsp;&nbsp; '''P''' &nbsp;= {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) ((''m'' | ''n'') &rArr; m = n)}<br />
<br />
:: = {''n'' &isin; '''N'''<sub>2</sub> ''':''' (&forall; ''m'' &isin; '''N'''<sub>2</sub>) (''m''&times;''m'' &le; ''n'' &rArr; &not;(''m'' | ''n''))}<br />
<br />
:: = '''N'''<sub>2</sub> \ {''n''&times;''m'' ''':''' ''n'',''m'' &isin; '''N'''<sub>2</sub>} <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''m'' ''':''' ''m'' &isin; '''N'''<sub>n</sub>} ''':''' ''n'' &isin; '''N'''<sub>2</sub> }<br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''N'''<sub>2</sub> } <br />
<br />
:: = '''N'''<sub>2</sub> \ '''&#8899;''' { {''n''&times;''n'', ''n''&times;''n''+''n'', ''n''&times;''n''+2&times;''n'', ...} ''':''' ''n'' &isin; '''P''' } <br />
:::: &nbsp; where &nbsp; &nbsp; '''N'''<sub>k</sub> = {''n'' &isin; '''N''' ''':''' ''n'' &ge; k}<br />
<br />
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><br />
<br />
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''. <br />
<br />
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.<br />
<br />
== Sieve of Eratosthenes ==<br />
<br />
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): <br />
<br />
<haskell><br />
primes = 2 : 3 : ([5,7..] `minus` _U [[p*p, p*p+2*p..] | p <- tail primes])<br />
<br />
-- Using `under n = takeWhile (< n)`, `minus` and `_U` satisfy<br />
-- under n (minus a b) == under n a \\ under n b<br />
-- under n (union a b) == nub . sort $ under n a ++ under n b<br />
-- under n . _U == nub . sort . concat . map (under n)<br />
</haskell><br />
<br />
The definition is primed with 2 and 3 as initial primes, to avoid the vicious circle.<br />
<br />
<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.<br />
<br />
Stepwise development follows (the fully developed version is [[#Tree merging with Wheel|here]]). <br />
<br />
=== Initial definition ===<br />
<br />
To start with, the sieve of Eratosthenes can be genuinely represented by <br />
<haskell><br />
-- genuine yet wasteful sieve of Eratosthenes<br />
primesTo m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p, p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [1..m])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs)) <br />
-- turner (p:xs) = p : turner [x | x <- xs, rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
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:<br />
<haskell><br />
-- ordered lists, difference and union<br />
minus (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : minus xs (y:ys)<br />
EQ -> minus xs ys <br />
GT -> minus (x:xs) ys<br />
minus xs _ = xs<br />
union (x:xs) (y:ys) = case (compare x y) of <br />
LT -> x : union xs (y:ys)<br />
EQ -> x : union xs ys <br />
GT -> y : union (x:xs) ys<br />
union xs [] = xs<br />
union [] ys = ys<br />
</haskell><br />
<br />
The name ''merge'' ought to be reserved for duplicates-preserving merging operation of mergesort.<br />
<br />
=== Analysis ===<br />
<br />
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].<br />
<br />
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.<br />
<br />
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. <br />
<br />
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>.<br />
<br />
=== From Squares ===<br />
<br />
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: <br />
<haskell><br />
primesToQ m = eratos [2..m] where<br />
eratos [] = []<br />
eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+p..m])<br />
-- eratos (p:xs) = p : eratos (xs `minus` map (p*) [p..div m p])<br />
-- eulers (p:xs) = p : eulers (xs `minus` map (p*) (takeWhile (<= div m p) (p:xs)))<br />
-- turner (p:xs) = p : turner [x | x<-xs, x<p*p || rem x p /= 0] <br />
</haskell><br />
<br />
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.<br />
<br />
<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><br />
<br />
=== Guarded ===<br />
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'':<br />
<haskell><br />
primesToG m = 2 : sieve [3,5..m] where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| otherwise = p : sieve (xs `minus` [p*p, p*p+2*p..])<br />
-- p : sieve (xs `minus` map (p*) [p,p+2..])<br />
-- p : eulers (xs `minus` map (p*) (p:xs)) <br />
</haskell><br />
(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.<br />
<br />
=== Accumulating Array ===<br />
<br />
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:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]]<br />
:: UArray Int Bool)<br />
where<br />
sieve p a <br />
| p*p > m = 2 : [i | (i,True) <- assocs a]<br />
| a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]]<br />
| otherwise = sieve (p+2) a<br />
</haskell><br />
<br />
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.<br />
<br />
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.<br />
<br />
=== Postponed ===<br />
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:<br />
<haskell><br />
primesPE1 = 2 : sieve [3..] primesPE1 <br />
where <br />
sieve xs (p:ps) | q <- p*p , (h,t) <- span (< q) xs =<br />
h ++ sieve (t `minus` [q, q+p..]) ps<br />
-- h ++ turner [x|x<-t, rem x p /= 0] ps<br />
</haskell><br />
<!-- primesPE1 = 2 : sieve [3,5..] 9 (tail primesPE1)<br />
where <br />
sieve xs q ~(p:t) | (h,ys) <- span (< q) xs =<br />
h ++ sieve (ys `minus` [q, q+2*p..]) (head t^2) t<br />
-- h ++ turner [x | x <- ys, rem x p /= 0] ...<br />
--><br />
Inlining and fusing <code>span</code> and <code>(++)</code> we get:<br />
<haskell><br />
primesPE = 2 : primes'<br />
where <br />
primes' = sieve [3,5..] 9 primes'<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| otherwise = sieve (xs `minus` [q, q+2*p..]) (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Segmented ===<br />
With work done segment-wise between the successive squares of primes it becomes <br />
<br />
<haskell><br />
primesSE = 2 : primes'<br />
where<br />
primes' = sieve 3 9 primes' []<br />
sieve x q ~(p:t) fs = <br />
foldr (flip minus) [x,x+2..q-2] <br />
[[y+s, y+2*s..q] | (s,y) <- fs]<br />
++ sieve (q+2) (head t^2) t<br />
((2*p,q):[(s,q-rem (q-y) s) | (s,y) <- fs])<br />
</haskell> <br />
<br />
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. <br />
<br />
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.<br />
<br />
====Segmented Tree-merging====<br />
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):<br />
<br />
<haskell><br />
primesSTE = 2 : primes' <br />
where <br />
primes' = sieve 3 9 primes' []<br />
sieve x q ~(p:t) fs = <br />
([x,x+2..q-2] `minus` joinST [[y+s, y+2*s..q] | (s,y) <- fs])<br />
++ sieve (q+2) (head t^2) t<br />
((++ [(2*p,q)]) [(s,q-rem (q-y) s) | (s,y) <- fs])<br />
<br />
joinST (xs:t) = (union xs . joinST . pairs) t where<br />
pairs (xs:ys:t) = union xs ys : pairs t<br />
pairs t = t<br />
joinST [] = []<br />
</haskell><br />
<br />
=== Linear merging ===<br />
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 by, 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:<br />
<haskell><br />
primesB = 2 : minus [3..] (foldr (\p r-> p*p : union [p*p+p, p*p+2*p..] r) [] primesB)<br />
</haskell><br />
or,<br />
<br />
<haskell><br />
primesLME1 = 2 : primes' where<br />
primes' = 3 : minus [5,7..] (joinL [[p*p, p*p+2*p..] | p <- primes'])<br />
<br />
joinL ((x:xs):t) = x : union xs (joinL t)<br />
</haskell><br />
<br />
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'').<br />
<br />
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 around ~ <math>n^{1.40}</math> (initially better, yet worsening for bigger ranges):<br />
<br />
<haskell><br />
primesLME = 2 : _Y ((3:) . minus [5,7..] . joinL . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
_Y :: (t -> t) -> t<br />
_Y g = g (_Y g) -- multistage, non-sharing, recursive<br />
-- g x where x = g x -- two stages, sharing, corecursive<br />
</haskell><br />
<br />
<code>_Y</code> is a non-sharing fixpoint combinator, here arranging for a recursive ''"telescoping"'' multistage primes production (a ''tower'' of producers).<br />
<br />
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.<br />
<br />
=== Tree merging ===<br />
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]]:<br />
<br />
<haskell><br />
primesTME = 2 : _Y ((3:) . gaps 5 . joinT . map (\p-> [p*p, p*p+2*p..]))<br />
<br />
joinT ((x:xs):t) = x : (union xs . joinT . pairs) t -- set union, ~=<br />
where pairs (xs:ys:t) = union xs ys : pairs t -- nub.sort.concat<br />
<br />
gaps k s@(x:xs) | k<x = k:gaps (k+2) s -- ~= [k,k+2..]\\s, <br />
| True = gaps (k+2) xs -- when null(s\\[k,k+2..])<br />
</haskell><br />
<br />
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).<br />
<br />
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>:<br />
<br />
[[Image:Tree-like_folding.gif|frameless|center|458px|tree-like folding]]<br />
<br />
=== Tree merging with Wheel ===<br />
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):<br />
<br />
<haskell><br />
primesTMWE = [2,3,5,7] ++ _Y ((11:) . tail . gapsW 11 wheel <br />
. joinT . hitsW 11 wheel)<br />
<br />
gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference<br />
| otherwise = gapsW (k+d) w cs -- k==c<br />
hitsW k (d:w) s@(p:ps) | k < p = hitsW (k+d) w s -- intersection<br />
| otherwise = scanl (\c d->c+p*d) (p*p) (d:w) <br />
: hitsW (k+d) w ps -- k==p <br />
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:<br />
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<br />
</haskell><br />
<br />
<br />
====Above Limit - Offset Sieve====<br />
Another task is to produce primes above a given value:<br />
<haskell><br />
{-# OPTIONS_GHC -O2 -fno-cse #-}<br />
primesFromTMWE primes m = dropWhile (< m) [2,3,5,7,11] <br />
++ gapsW a wh' (compositesFrom a)<br />
where<br />
(a,wh') = rollFrom (snapUp (max 3 m) 3 2)<br />
(h,p':t) = span (< z) $ drop 4 primes -- p < z => p*p<=a<br />
z = ceiling $ sqrt $ fromIntegral a + 1 -- p'>=z => p'*p'>a<br />
compositesFrom a = joinT (joinST [multsOf p a | p <- h ++ [p']]<br />
: [multsOf p (p*p) | p <- t] )<br />
<br />
snapUp v o step = v + (mod (o-v) step) -- full steps from o<br />
multsOf p from = scanl (\c d->c+p*d) (p*x) wh -- map (p*) $<br />
where -- scanl (+) x wh<br />
(x,wh) = rollFrom (snapUp from p (2*p) `div` p) -- , if p < from <br />
wheelNums = scanl (+) 0 wheel<br />
rollFrom n = go wheelNums wheel <br />
where m = (n-11) `mod` 210 <br />
go (x:xs) ws@(w:ws') | x < m = go xs ws'<br />
| True = (n+x-m, ws) -- (x >= m)<br />
</haskell><br />
<br />
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:<br />
<br />
<haskell><br />
primesFrom m = filter isPrime [m..]<br />
</haskell><br />
<br />
=== Map-based ===<br />
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:<br />
<br />
<haskell><br />
import Data.List -- based on http://stackoverflow.com/a/1140100<br />
import qualified Data.Map as M<br />
<br />
primesMPE :: [Integer]<br />
primesMPE = 2:mkPrimes 3 M.empty prs 9 -- postponed addition of primes into map;<br />
where -- decoupled primes loop feed <br />
prs = 3:mkPrimes 5 M.empty prs 9<br />
mkPrimes n m ps@ ~(p:t) q = case (M.null m, M.findMin m) of<br />
(False, (n', skips)) | n == n' -><br />
mkPrimes (n+2) (addSkips n (M.deleteMin m) skips) ps q<br />
_ -> if n<q<br />
then n : mkPrimes (n+2) m ps q<br />
else mkPrimes (n+2) (addSkip n m (2*p)) t (head t^2)<br />
<br />
addSkip n m s = M.alter (Just . maybe [s] (s:)) (n+s) m<br />
addSkips = foldl' . addSkip<br />
</haskell><br />
<br />
== Turner's sieve - Trial division ==<br />
<br />
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:<br />
<br />
<haskell><br />
-- unbounded sieve, premature filters<br />
primesT = sieve [2..]<br />
where<br />
sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- map fst . tail <br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..])<br />
</haskell><br />
<br />
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.<br />
<br />
=== Guarded Filters ===<br />
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):<br />
<br />
<haskell><br />
primesToGT m = sieve [2..m]<br />
where<br />
sieve (p:xs) <br />
| p*p > m = p : xs<br />
| True = p : sieve [x | x <- xs, rem x p /= 0]<br />
-- (\(a,(p,xs):_)-> map fst a ++ p:xs) . span ((< m).(^2).fst) . tail<br />
-- $ iterate (\(_,p:xs)->(p, [x | x <- xs, rem x p /= 0])) (1,[2..m])<br />
</haskell><br />
<br />
=== Postponed Filters ===<br />
Or it can remain unbounded, just filters creation must be ''postponed'' until the right moment:<br />
<haskell><br />
primesPT1 = 2 : sieve primesPT1 [3..] <br />
where <br />
sieve (p:ps) xs = let (h,t) = span (< p*p) xs <br />
in h ++ sieve ps [x | x<-t, rem x p /= 0]<br />
-- fix $ concat . map fst . <br />
-- iterate (\(_,(xs,p:ps))->let (h,t)=span (< p*p) xs in<br />
-- (h, ([x | x <- t, rem x p /= 0], ps))) . ((,) [2]) . ((,) [3..])<br />
</haskell><br />
This is better re-written with <code>span</code> and <code>(++)</code> inlined and fused into the <code>sieve</code>:<br />
<haskell><br />
primesPT = 2 : primes'<br />
where <br />
primes' = sieve [3,5..] 9 primes'<br />
sieve (x:xs) q ps@ ~(p:t)<br />
| x < q = x : sieve xs q ps<br />
| True = sieve [x | x <- xs, rem x p /= 0] (head t^2) t<br />
</haskell><br />
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.<br />
<br />
=== Optimal trial division ===<br />
<br />
The above is equivalent to the traditional formulation of trial division,<br />
<haskell><br />
ps = 2 : [i | i <- [3..], <br />
and [rem i p > 0 | p <- takeWhile ((<=i).(^2)) ps]]<br />
</haskell><br />
or,<br />
<haskell><br />
noDivs n fs = foldr (\f r -> f*f > n || (rem n f /= 0 && r)) True fs<br />
-- primes = filter (`noDivs`[2..]) [2..]<br />
primesTD = 2 : 3 : filter (`noDivs` tail primesTD) [5,7..]<br />
isPrime n = n > 1 && noDivs n primesTD<br />
</haskell><br />
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.<br />
<br />
Trial division is used as a simple [[Testing primality#Primality Test and Integer Factorization|primality test and prime factorization algorithm]].<br />
<br />
=== Segmented Generate and Test ===<br />
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. <br />
<haskell><br />
import Data.List<br />
<br />
primesST = 2 : oddprimes<br />
where<br />
oddprimes = sieve 3 9 oddprimes (inits oddprimes) -- [],[3],[3,5],...<br />
sieve x q ~(_:t) (fs:ft) =<br />
filter ((`all` fs) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head t^2) t ft<br />
</haskell><br />
<br />
<br />
==== Generate and Test Above Limit ====<br />
<br />
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:<br />
<br />
<haskell><br />
primesFromST m | m > 2 =<br />
sieve (m`div`2*2+1) (head ps^2) (tail ps) (inits ps)<br />
where <br />
(h,ps) = span (<= (floor.sqrt $ fromIntegral m+1)) oddprimes<br />
sieve x q ps (fs:ft) =<br />
filter ((`all` (h ++ fs)) . ((/=0).) . rem) [x,x+2..q-2]<br />
++ sieve (q+2) (head ps^2) (tail ps) ft<br />
oddprimes = 3 : primesFromST 5 -- odd primes<br />
</haskell><br />
<br />
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.<br />
<br />
=== Conclusions ===<br />
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.<br />
<br />
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.<br />
<br />
== Euler's Sieve ==<br />
=== Unbounded Euler's sieve ===<br />
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:<br />
<br />
<haskell><br />
primesEU = 2 : eulers [3,5..] where<br />
eulers (p:xs) = p : eulers (xs `minus` map (p*) (p:xs))<br />
-- eratos (p:xs) = p : eratos (xs `minus` [p*p, p*p+2*p..])<br />
</haskell><br />
<br />
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.<br />
<br />
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. <br />
<br />
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.<br />
<br />
=== Wheeled list representation ===<br />
<br />
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:<br />
<haskell><br />
{- fromElt (x,i) = x : fromElt (x + i,i)<br />
=== iterate (+ i) x<br />
[n..] === fromElt (n,1) <br />
=== fromSpan ([n],1) <br />
[n,n+2..] === fromElt (n,2) <br />
=== fromSpan ([n,n+2],4) -}<br />
<br />
fromSpan (xs,i) = xs ++ fromSpan (map (+ i) xs,i)<br />
<br />
{- === concat $ iterate (map (+ i)) xs<br />
fromSpan (p:xt,i) === p : fromSpan (xt ++ [p + i], i) <br />
fromSpan (xs,i) `minus` fromSpan (ys,i) <br />
=== fromSpan (xs `minus` ys, i) <br />
map (p*) (fromSpan (xs,i)) <br />
=== fromSpan (map (p*) xs, p*i)<br />
fromSpan (xs,i) === forall (p > 0).<br />
fromSpan (concat $ take p $ iterate (map (+ i)) xs, p*i) -}<br />
<br />
spanSpecs = iterate eulerStep ([2],1)<br />
eulerStep (xs@(p:_), i) = <br />
( (tail . concat . take p . iterate (map (+ i))) xs<br />
`minus` map (p*) xs, p*i )<br />
<br />
{- > mapM_ print $ take 4 spanSpecs <br />
([2],1)<br />
([3],2)<br />
([5,7],6)<br />
([7,11,13,17,19,23,29,31],30) -}<br />
</haskell><br />
<br />
Generating a list from a span specification is like rolling a ''[[#Prime_Wheels|wheel]]'' as its pattern gets repeated over and over again. For each span specification <code>w@((p:_),_)</code> produced by <code>eulerStep</code>, the numbers in <code>(fromSpan w)</code> up to <math>{p^2}</math> are all primes too, so that<br />
<br />
<haskell><br />
eulerPrimesTo m = if m > 1 then go ([2],1) else []<br />
where<br />
go w@((p:_), _) <br />
| m < p*p = takeWhile (<= m) (fromSpan w)<br />
| True = p : go (eulerStep w)<br />
</haskell><br />
<br />
This runs at about <math>O(n^{1.5..1.8})</math> complexity, for <code>n</code> primes produced, and also suffers from a severe space leak problem (IOW its memory usage is also very high).<br />
<br />
== Using Immutable Arrays ==<br />
<br />
=== Generating Segments of Primes ===<br />
<br />
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:<br />
<br />
<haskell><br />
import Data.Array.Unboxed<br />
<br />
primesSA :: [Int]<br />
primesSA = 2 : prs<br />
where <br />
prs = 3 : sieve prs 3 []<br />
sieve (p:ps) x fs = [i*2 + x | (i,True) <- assocs a] <br />
++ sieve ps (p*p) ((p,0) : <br />
[(s, rem (y-q) s) | (s,y) <- fs])<br />
where<br />
q = (p*p-x)`div`2<br />
a :: UArray Int Bool<br />
a = accumArray (\ b c -> False) True (1,q-1)<br />
[(i,()) | (s,y) <- fs, i <- [y+s, y+s+s..q]] <br />
</haskell><br />
<br />
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.<br />
<br />
=== Calculating Primes Upto a Given Value ===<br />
<br />
Equivalent to [[#Accumulating Array|Accumulating Array]] above, running somewhat faster (compiled by GHC with optimizations turned on):<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -O2 #-}<br />
import Data.Array.Unboxed<br />
<br />
primesToNA n = 2: [i | i <- [3,5..n], ar ! i]<br />
where<br />
ar = f 5 $ accumArray (\ a b -> False) True (3,n) <br />
[(i,()) | i <- [9,15..n]]<br />
f p a | q > n = a<br />
| True = if null x then a' else f (head x) a'<br />
where q = p*p<br />
a' :: UArray Int Bool<br />
a'= a // [(i,False) | i <- [q, q+2*p..n]]<br />
x = [i | i <- [p+2,p+4..n], a' ! i]<br />
</haskell><br />
<br />
=== Calculating Primes in a Given Range ===<br />
<br />
<haskell><br />
primesFromToA a b = (if a<3 then [2] else []) <br />
++ [i | i <- [o,o+2..b], ar ! i]<br />
where <br />
o = max (if even a then a+1 else a) 3 -- first odd in the segment<br />
r = floor . sqrt $ fromIntegral b + 1<br />
ar = accumArray (\_ _ -> False) True (o,b) -- initially all True,<br />
[(i,()) | p <- [3,5..r]<br />
, let q = p*p -- flip every multiple of an odd <br />
s = 2*p -- to False<br />
(n,x) = quotRem (o - q) s <br />
q' = if o <= q then q<br />
else q + (n + signum x)*s<br />
, i <- [q',q'+s..b] ]<br />
</haskell><br />
<br />
Although sieving by odds instead of by 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.<br />
<br />
== Using Mutable Arrays ==<br />
<br />
Using mutable arrays is the fastest but not the most memory efficient way to calculate prime numbers in Haskell.<br />
<br />
=== Using ST Array ===<br />
<br />
This method implements the Sieve of Eratosthenes, similar to how you might do it<br />
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.<br />
<br />
<haskell><br />
import Control.Monad<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Unboxed<br />
<br />
sieveUA :: Int -> UArray Int Bool<br />
sieveUA top = runSTUArray $ do<br />
let m = (top-1) `div` 2<br />
r = floor . sqrt $ fromIntegral top + 1<br />
sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool)<br />
forM_ [1..r `div` 2] $ \i -> do<br />
isPrime <- readArray sieve i<br />
when isPrime $ do -- ((2*i+1)^2-1)`div`2 == 2*i*(i+1)<br />
forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do<br />
writeArray sieve j False<br />
return sieve<br />
<br />
primesToUA :: Int -> [Int]<br />
primesToUA top = 2 : [i*2+1 | (i,True) <- assocs $ sieveUA top]<br />
</haskell><br />
<br />
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)''.<br />
<br />
=== Bitwise prime sieve with Template Haskell ===<br />
<br />
Count the number of prime below a given 'n'. Shows fast bitwise arrays,<br />
and an example of [[Template Haskell]] to defeat your enemies.<br />
<br />
<haskell><br />
{-# OPTIONS -O2 -optc-O -XBangPatterns #-}<br />
module Primes (nthPrime) where<br />
<br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
import Data.Array.Base<br />
import System<br />
import Control.Monad<br />
import Data.Bits<br />
<br />
nthPrime :: Int -> Int<br />
nthPrime n = runST (sieve n)<br />
<br />
sieve n = do<br />
a <- newArray (3,n) True :: ST s (STUArray s Int Bool)<br />
let cutoff = truncate (sqrt $ fromIntegral n) + 1<br />
go a n cutoff 3 1<br />
<br />
go !a !m cutoff !n !c<br />
| n >= m = return c<br />
| otherwise = do<br />
e <- unsafeRead a n<br />
if e then<br />
if n < cutoff then<br />
let loop !j<br />
| j < m = do<br />
x <- unsafeRead a j<br />
when x $ unsafeWrite a j False<br />
loop (j+n)<br />
| otherwise = go a m cutoff (n+2) (c+1)<br />
in loop ( if n < 46340 then n * n else n `shiftL` 1)<br />
else go a m cutoff (n+2) (c+1)<br />
else go a m cutoff (n+2) c<br />
</haskell><br />
<br />
And place in a module:<br />
<br />
<haskell><br />
{-# OPTIONS -fth #-}<br />
import Primes<br />
<br />
main = print $( let x = nthPrime 10000000 in [| x |] )<br />
</haskell><br />
<br />
Run as:<br />
<br />
<haskell><br />
$ ghc --make -o primes Main.hs<br />
$ time ./primes<br />
664579<br />
./p