0

I implemented a Fibonacci function in Scala and it works fine however when I enter 50 it takes a long time to compute it because it has to calculate the 2 previous integers each time. I found a function that keeps the 2 previous numbers. However, can somebody tell me how to write this function to make it accept 2 integers instead of 3 and return the last 2 numbers to compute the Fibonacci at a particular index x. Thanks!

    def fastFib(x: Long ): Long = {
      def fast(x:Long , a:Long, b:Long):Long = 
      if (x<=0) a+b 
      else fast(x-1,b,a+b)
      if (x<2) 1 
      else fast(x-2,0,1)
   }
Andrzej Jozwik
  • 14,331
  • 3
  • 59
  • 68
user2947615
  • 491
  • 3
  • 5
  • 14

1 Answers1

0

You can cache the intermediate results, then you never recompute the same result twice

Here is the code

//this supposed to contains all the value when initialized
//initialized with 0 for all value
val cache = Array [Int] (101);//0 to 100
cache(1)==1;//initial value
cache(2)=1;//initial value

def fibonacciCache(n:Int) : Int = {
  if (n>100)
  {
      println("error");
      return -1;
  }

  if (cache(n)!=0)//means value has been calculated
     return cache(n);
  else
  {
    cache(n)=fibonacciCache(n-1)+fibonacciCache(n-2);
    return cache(n);    
  }
}

Hope that helps

Gabriel
  • 3,564
  • 1
  • 27
  • 49