Can someone explain why this is throwing a stackoverflow error? (Scala, lazylist, nth prime number)

47 Views Asked by At

The Scala snippet below finds the nth prime number up to the 6500th (indexed from 0) on my machine. Calling it with primes(6500) returns 65071. After this (say, primes(6501)), it throws a stackoverflowerror. Any suggestions for improving it? Newbie to Scala, trying to teach myself the language - probably doing some awful stuff.

def primes: LazyList[Int] = { 
  def sieve(xs: LazyList[Int]): LazyList[Int] = {
    val p = xs.head
    p #:: sieve(xs.tail.filter(_ % p != 0))
  }
  sieve(LazyList.from(2))
}

I do not know where I can go from here...

0

There are 0 best solutions below