Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Scala | Sieve of Eratosthenes

The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers smaller than a given integer n when n is smaller than 106 or so.

Here's how the Sieve of Eratosthenes works:

  1. Create a boolean array prime[0...n] and initialize all entries as true. A value in prime[i] will be false if i is not a prime, else true.

  2. Start from the first prime number, which is 2, and mark all of its multiples as not prime.

  3. Move to the next number and repeat the process until n​.

  4. The remaining numbers which are marked as true in the list are all prime numbers less than n.

Let's implement the Sieve of Eratosthenes in Scala:

object SieveOfEratosthenes {

  def sieve(n: Int): List[Int] = {
    val prime = Array.fill(n + 1)(true)
    prime(0) = false
    prime(1) = false
    val sqrtN = math.sqrt(n).toInt

    for (p <- 2 to sqrtN if prime(p)) {
      for (i <- p * p to n by p) {
        prime(i) = false
      }
    }

    for (i <- 2 to n if prime(i)) yield i
  }.toList

  def main(args: Array[String]): Unit = {
    val n = 100
    println(s"Prime numbers up to $n:")
    println(sieve(n).mkString(", "))
  }
}

Running the main method of the SieveOfEratosthenes object will print the prime numbers up to 100. You can adjust the value of n to find primes up to any desired value.

  1. Scala Sieve of Eratosthenes Implementation:

    The classic Sieve of Eratosthenes algorithm in Scala.

    def sieveOfEratosthenes(limit: Int): List[Int] = {
      val sieve = Array.fill(limit + 1)(true)
      sieve(0) = false
      sieve(1) = false
    
      for (i <- 2 to Math.sqrt(limit).toInt; if sieve(i)) {
        (i * i to limit by i).foreach(j => sieve(j) = false)
      }
    
      sieve.zipWithIndex.collect { case (isPrime, idx) if isPrime => idx }.toList
    }
    
  2. Functional Programming Sieve of Eratosthenes in Scala:

    A functional programming style implementation.

    def functionalSieve(limit: Int): List[Int] =
      Stream.from(2)
        .filter(n => (2 until Math.sqrt(n).toInt + 1).forall(n % _ != 0))
        .takeWhile(_ <= limit)
        .toList
    
  3. Prime Number Generation in Scala Using Sieve of Eratosthenes:

    Generate prime numbers up to a given limit.

    val primes = sieveOfEratosthenes(50)
    
  4. Efficient Prime Number Sieve in Scala:

    An efficient Sieve of Eratosthenes implementation with optimizations.

    def optimizedSieve(limit: Int): List[Int] = {
      val sieve = Array.fill(limit + 1)(true)
      sieve(0) = false
      sieve(1) = false
    
      for {
        i <- 2 to Math.sqrt(limit).toInt
        if sieve(i)
        j <- i * i to limit by i
      } sieve(j) = false
    
      sieve.zipWithIndex.collect { case (isPrime, idx) if isPrime => idx }.toList
    }
    
  5. Scala Sieve of Eratosthenes Example Code:

    Example usage of the Sieve of Eratosthenes.

    val primes = sieveOfEratosthenes(30)
    
  6. Functional Approach to Sieve of Eratosthenes in Scala:

    A functional approach to the Sieve of Eratosthenes using Streams.

    val functionalPrimes = functionalSieve(30)
    
  7. Optimizing Sieve of Eratosthenes in Scala:

    Optimizations to improve the efficiency of the Sieve.

    val optimizedPrimes = optimizedSieve(30)
    
  8. Parallel Sieve of Eratosthenes in Scala:

    A parallel implementation for increased performance.

    import scala.collection.parallel.CollectionConverters._
    
    def parallelSieve(limit: Int): List[Int] =
      (2 to limit).par
        .filter(n => (2 until Math.sqrt(n).toInt + 1).forall(n % _ != 0))
        .toList