Sha256: d3644ed618bc345f7022128d76a97302249e5dbe8d1f0ce9670969f3f4f35b38

Contents?: true

Size: 844 Bytes

Versions: 203

Compression:

Stored size: 844 Bytes

Contents

import scala.collection.mutable

object Sieve {
  def primesUpTo(upperBound: Int): List[Int] = {
    // Start with set of all "possible" values that could be prime
    val primes = mutable.HashSet.empty ++ (2 to upperBound)

    // Remove multiples of a possiblePrime from the primes set.
    def checkPrime(possiblePrime: Int) {
      if (primes contains possiblePrime) {
        // remove multiples of possiblePrime from set
        val possibleSquared = possiblePrime * possiblePrime
        for (i <- possibleSquared to upperBound by possiblePrime) {
          primes.remove(i)
        }
      }
    }

    val sqrtUpper = math.sqrt(upperBound).toInt
    for (possible <- 2 to sqrtUpper) {
      checkPrime(possible)
    }

    // Return the remaining items in the set as a sorted list - these are the primes
    primes.toList.sorted
  }
}

Version data entries

203 entries across 203 versions & 1 rubygems

Version Path
trackler-2.1.0.48 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.47 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.46 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.45 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.44 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.43 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.42 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.41 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.40 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.39 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.38 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.37 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.36 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.34 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.33 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.32 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.31 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.30 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.29 tracks/scala/exercises/sieve/example.scala
trackler-2.1.0.28 tracks/scala/exercises/sieve/example.scala