 # Ric0chet's solution

## to Sieve in the Scala Track

Published at Sep 30 2019 · 0 comments
Instructions
Test suite
Solution

Use the Sieve of Eratosthenes to find all the primes from 2 up to a given number.

The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.

Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit])

The algorithm consists of repeating the following over and over:

• take the next available unmarked number in your list (it is prime)
• mark all the multiples of that number (they are not prime)

Repeat until you have processed each number in your range.

When the algorithm terminates, all the numbers in the list that have not been marked are prime.

The wikipedia article has a useful graphic that explains the algorithm: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Notice that this is a very specific algorithm, and the tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

For more detailed info about the Scala track see the help page.

## Source

Sieve of Eratosthenes at Wikipedia http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### SieveTest.scala

``````import org.scalatest.{Matchers, FunSuite}

/** @version 1.1.0 */
class SieveTest extends FunSuite with Matchers {

test("no primes under two") {
Sieve.primes(1) should be(List())
}

test("find first prime") {
pending
Sieve.primes(2) should be(List(2))
}

test("find primes up to 10") {
pending
Sieve.primes(10) should be(List(2, 3, 5, 7))
}

test("limit is prime") {
pending
Sieve.primes(13) should be(List(2, 3, 5, 7, 11, 13))
}

test("find primes up to 1000") {
pending
Sieve.primes(1000) should be(
List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647,
653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997))
}
}``````
``````import scala.collection.mutable._
//  09-28-19

object Sieve {
def primes(lim: Int): List[Int] ={
if (lim < 2) return List()

usingListReduction(lim)
//    usingDualLoops(lim)
//    usingNestedLoopsOdds(lim)
//    usingNestedLoopsAll(lim)

//    usingRecursion(lim)
//    usingTailRec(lim)
//    usingFilteredStream(lim)
//    usingInefficientSieve(lim)
}

// 73 ms
private def usingListReduction(lim: Int): List[Int] =
(2 to lim / 2).foldLeft((2 to lim).toBuffer) { (primes, i) =>
primes --= ((i * 2) to lim by i)  // instead of foreach
}.toList

// 49 ms -- checking odds to sqrt(lim)
private def usingDualLoops(lim: Int): List[Int] = {
val sieve = Array.fill(lim - 1) { false }
val primes = ListBuffer[Int](2)

for (i <- 3 to math.sqrt(lim.toDouble).toInt by 2) {
for (j <- (i * i) to lim by i) { sieve(j - 2) = true }
}
for (k <- sieve.indices) {
if (!sieve(k) && (k % 2 != 0)) primes += (k + 2)
}
primes.toList
}

// 41 ms
private def usingNestedLoopsOdds(lim: Int): List[Int] = {
val sieve = Array.fill(lim + 1) { false }
val primes = ListBuffer[Int](2)

for (i <- 3 to lim by 2) {
if (!sieve(i)) {
for (p <- (i * i) until lim by i) {
sieve(p) = true
}
primes += i
}
}
primes.toList
}

// 44 ms
private def usingNestedLoopsAll(lim: Int): List[Int] = {
val sieve = Array.fill(lim + 1) { false }
val primes = ListBuffer[Int]()

for (i <- 2 to lim) {
if (!sieve(i)) {
for (p <- (i * 2) to lim by i) {
sieve(p) = true
}
primes += i
}
}
primes.toList
}

// ----------------------------------------

// 67 ms -- Jaratma's solution
private def usingRecursion(lim: Int): List[Int] = {
def sieve(ls: List[Int]): List[Int] =
case None => ls
}

sieve((2 to lim).toList)
}

// 48 ms -- ALRW's solution
private def usingTailRec(lim: Int): List[Int] = {
@annotation.tailrec
def sieve(init: List[Int], primes: List[Int] = List()): List[Int] =
init match {
case Nil => primes
case x :: xs => sieve(xs.filterNot(_ % x == 0), primes :+ x)
}

sieve((2 to lim).toList)
}

// 77 ms -- Malokroman's solution
private def usingFilteredStream(lim: Int): List[Int] =
primes.takeWhile { _ <= lim }.toList

private val primes: Stream[Int] = 2 #:: Stream.from(3).filter { i =>
primes.takeWhile { k => k * k <= i }.forall { i % _ > 0 }
}

// 751 ms
private def usingInefficientSieve(lim: Int): List[Int] =
(2 to lim / 2).foldLeft((2 to lim).toBuffer) { (sieve, i) =>
(i + 1 to lim).foreach { it =>
if (sieve.contains(it) && it % i == 0) sieve -= it
}
sieve
}.toList
}``````