Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Not really answering the question but since I spent some times benchmarking various combinations...</p> <p>You can get better performance if you use <code>Iterator</code>, <code>ArrayBuffer</code> and avoid <code>takeWhile</code> in the inner loop, to minimize memory allocations.</p> <pre><code>def primes2(): Stream[Int] = { def sieve(p: Int, ps: ArrayBuffer[Int]): Stream[Int] = { def hasNoDivisor(prime_? :Int, j: Int = 0): Boolean = { val n = ps(j) if (n*n &gt; prime_?) true else if (prime_? % n == 0) false else hasNoDivisor(prime_?, j+1) } p #:: { val nextprime = Iterator.from(ps.last + 2, 2).find(hasNoDivisor(_)).get sieve(nextprime, ps += nextprime) } } sieve(3, ArrayBuffer(3)) } </code></pre> <p>Here is a version with <code>Iterator</code> instead of <code>Stream</code>, it's faster and you can always use <code>primes3().toStream</code> to get a Stream if needed.</p> <pre><code>def primes3() = List(2,3).iterator ++ new Iterator[Int] { val ps = ArrayBuffer[Int](3) def hasNoDivisor(prime_? :Int, j: Int = 0): Boolean = { val n = ps(j) if (n*n &gt; prime_?) true else if (prime_? % n == 0) false else hasNoDivisor(prime_?, j+1) } def hasNext = true def next() = { val nextprime = Iterator.from(ps.last + 2, 2).find(hasNoDivisor(_)).get ps += nextprime nextprime } } </code></pre> <p>Results:</p> <pre><code>primes : warming... primes : running... primes : elapsed: 3.711 res39: Int = 283145 primes2: warming... primes2: running... primes2: elapsed: 1.039 res40: Int = 283145 primes3: warming... primes3: running... primes3: elapsed: 0.530 res41: Int = 283146 </code></pre> <p>I also tried replacing <code>from</code>, <code>find</code> and <code>hasNoDivisor</code> with a couple of <code>while</code> loops, and that was faster, but less comprehensible.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    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