I am currently using Project Euler to learn Scala.
I am stuck on problem 25 with a java.lang.OutOfMemoryError exception.
Here is the question:
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
What I have come up with:
def fibonacciIndex(numOfDigits: Int): Option[Int] = {
lazy val fibs: LazyList[Int] = 0 #:: fibs.scanLeft(1)(_ + _)
fibs.find(_.toString.length == numOfDigits)
}
I am trying to do this in a purely functional way.
Has anyone got some suggestions to improve the memory usage?
Thanks in advance!
EDIT: I was overflowing the Int type. Solved like so:
def fibonacciIndex(numOfDigits: Int): Int = {
lazy val bigFibs: LazyList[BigInt] = BigInt(0) #:: bigFibs.scanLeft(BigInt(1))(_ + _)
bigFibs.indexWhere(_.toString.length == numOfDigits)
}