Question

I want to find prime numbers using collection functions. I generate numbers from 1 to 10000 then I decide to take first number starting from 2, let's name it X and replace it with -1 or delete where X%Y === 0 Y is any numbers after X.

Code:

val list = (2 to 10000)
println(list.map(x => list.filter(y => y % x == 0)))

but this code wrong, ugly, have so bad performance how can I do it truly functional way?

Was it helpful?

Solution

I solved the same task with this:

import scala.annotation.tailrec

def primesBelow(x: Int): List[Int] = {
  @tailrec
  def iter(primes: List[Int], xs: List[Int]): List[Int] = xs match {
    case Nil => primes
    case x :: xs => iter(x :: primes, xs.filter(_ % x != 0))
  }
  iter(Nil, (2 until x).toList).reverse
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top