Now I'm trying to find out Scala. I started a little work by writing some simple algorithms. I ran into some problems when I wanted to implement the Sith algorithm to find all all primes below a certain threshold.
My implementation:
import scala.math
object Sieve {
def getPrimes(maxNum : Int) = {
def sieve(list: List[Int], stop : Int) : List[Int] = {
list match {
case Nil => Nil
case h :: list if h <= stop => h :: sieve(list.filterNot(_ % h == 0), stop)
case _ => list
}
}
val stop : Int = math.sqrt(maxNum).toInt
sieve((2 to maxNum).toList, stop)
}
def main(args: Array[String]) = {
val ap = printf("%d ", (_:Int));
getPrimes(1000).foreach(ap(_))
getPrimes(100000).foreach(ap(_))
getPrimes(1000000).foreach(ap(_))
}
}
Unfortunately, it fails when I want to calculate all primes less than 1,000,000 (1 million). I get OutOfMemory.
Do you have any idea on how to optimize the code, or how I can implement this algorithm more elegantly.
PS: I did something very similar in Haskell, and there I did not encounter any problems.
source
share