Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting functional sieve of Eratosthenes fast
    primarykey
    data
    text
    <p>I read <a href="https://stackoverflow.com/questions/2325914/haskell-f-turners-sieve/5702990">this other post about a F# version of this algorithm</a>. I found it very elegant and tried to combine some ideas of the answers.</p> <p>Although I optimized it to make fewer checks (check only numbers around 6) and leave out unnecessary caching, it is still painfully slow. Calculating the 10,000<sup>th</sup> prime already take more than 5 minutes. Using the imperative approach, I can test all 31-bit integers in not that much more time.</p> <p>So my question is if I am missing something that makes all this so slow. For example in <a href="https://stackoverflow.com/questions/4629734/the-sieve-of-eratosthenes-in-f">another post</a> someone was speculating that <code>LazyList</code> may use locking. Does anyone have an idea?</p> <p>As StackOverflow's rules say not to post new questions as answers, I feel I have to start a new topic for this.</p> <p>Here's the code:</p> <pre><code>#r "FSharp.PowerPack.dll" open Microsoft.FSharp.Collections let squareLimit = System.Int32.MaxValue |&gt; float32 |&gt; sqrt |&gt; int let around6 = LazyList.unfold (fun (candidate, (plus, next)) -&gt; if candidate &gt; System.Int32.MaxValue - plus then None else Some(candidate, (candidate + plus, (next, plus))) ) (5, (2, 4)) let (|SeqCons|SeqNil|) s = if Seq.isEmpty s then SeqNil else SeqCons(Seq.head s, Seq.skip 1 s) let rec lazyDifference l1 l2 = if Seq.isEmpty l2 then l1 else match l1, l2 with | LazyList.Cons(x, xs), SeqCons(y, ys) -&gt; if x &lt; y then LazyList.consDelayed x (fun () -&gt; lazyDifference xs l2) elif x = y then lazyDifference xs ys else lazyDifference l1 ys | _ -&gt; LazyList.empty let lazyPrimes = let rec loop = function | LazyList.Cons(p, xs) as ll -&gt; if p &gt; squareLimit then ll else let increment = p &lt;&lt;&lt; 1 let square = p * p let remaining = lazyDifference xs {square..increment..System.Int32.MaxValue} LazyList.consDelayed p (fun () -&gt; loop remaining) | _ -&gt; LazyList.empty loop (LazyList.cons 2 (LazyList.cons 3 around6)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload