Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few potential issues, although I don't really see a single "smoking gun"... Anyway, here's what I've got. First:</p> <pre><code>sieve.map(x =&gt; if (x % seed == 0 &amp;&amp; x &gt; seed) 0 else x).filter(_ &gt; 0) </code></pre> <p>could be written more concisely as:</p> <pre><code>sieve.filter(x =&gt; x &lt;= seed || x % seed != 0) </code></pre> <p>Next, <code>upper</code> is unused in <code>filterPrimes</code> (this should have no effect on performance though).</p> <p>Third, don't use a <code>var</code> and a <code>for</code> loop if you want to really use a pure functional style, instead turn <code>filterPrimes</code> into a tail-recursive function. The compiler might be clever enough to optimize away the copies if you do it this way (although I wouldn't hold my breath).</p> <p>Finally, and probably most importantly, your <code>for</code> loop is wasting a huge amount of time filtering out values that have necessarily already been filtered. For example, it tries to filter multiples of 4 after already having filtered all multiples of 2. If you want to use this sieve algorithm efficiently, you need to choose your seeds from the remaining elements in the list.</p> <p>In other words, keep an <em>index</em> into the list, and determine the seed from the index, like:</p> <pre><code>iteration 0: 2 3 4 5 6 7 8 9 ... index: ^ iteration 1: 2 3 5 7 9 ... index: ^ iteration 2: 2 3 5 7 ... index: ^ </code></pre> <p>this avoids the duplicate effort. Also, you don't need to keep iterating until you get to <code>max</code>, I think you can actually stop when you get past <code>sqrt(max)</code>.</p>
 

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