Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to write Fibonacci function in Scala?

I've looked over a few implementations of Fibonacci function in Scala starting from a very simple one, to the more complicated ones.

I'm not entirely sure which one is the fastest. I'm leaning towards the impression that the ones that uses memoization is faster, however I wonder why Scala doesn't have a native memoization.

Can anyone enlighten me toward the best and fastest (and cleanest) way to write a fibonacci function?

like image 412
Enrico Susatyo Avatar asked Sep 12 '11 13:09

Enrico Susatyo


People also ask

How do you write Fibonacci series in Scala?

Fibonacci numbers in Scala object Fibonacci { def fibonacci(n: Int): Int = if (n < 3) 1 else fibonacci(n - 1) + fibonacci(n - 2) def main(args: Array[String]) { for {i <- List. range(1, 17)} yield { print(fibonacci(i) + ", ") } println("...") } }

How do you express the Fibonacci sequence?

The Fibonacci sequence formula deals with the Fibonacci sequence, finding its missing terms. The Fibonacci formula is given as, Fn = Fn-1 + Fn-2, where n > 1.

What is f9 Fibonacci sequence?

F(9)=34. F(10)=55. F(11)=89. F(12)=144. F(13)=233.


1 Answers

The fastest versions are the ones that deviate from the usual addition scheme in some way. Very fast is the calculation somehow similar to a fast binary exponentiation based on these formulas:

F(2n-1) = F(n)² + F(n-1)²
F(2n) = (2F(n-1) + F(n))*F(n)

Here is some code using it:

def fib(n:Int):BigInt = {
   def fibs(n:Int):(BigInt,BigInt) = if (n == 1) (1,0) else {
     val (a,b) = fibs(n/2)
     val p = (2*b+a)*a
     val q = a*a + b*b
     if(n % 2 == 0) (p,q) else (p+q,p)
   }
   fibs(n)._1
}

Even though this is not very optimized (e.g. the inner loop is not tail recursive), it will beat the usual additive implementations.

like image 137
Landei Avatar answered Oct 11 '22 09:10

Landei