xamples
epeat
ode
pproach
ptimize
est
Write a recursive solution to find the nth number in the Fibonacci sequence
Fibonacci Sequence is 0, 1, 1, 2, 3, 5, 8, 13...
Mathematically Fn = Fn-1 + Fn-2
In words, each number in the sequence is the sum of the previous two integer values. The sequence is started with the numbers 0, 1.
*Bonus: This is an easy solution to the classic stair problem. Given n stairs, how many combinations exist if you can climb 1 or 2 stairs at a time.*
fibonacci(7) // returns 13
Note, we start our Fibonacci Sequence at index 0, thus n=7 is 13. 0, 1, 1, 2, 3, 5, 8, 13...
function fibonacci(num){
if(num > 2) return fibonacci(num - 1) + fibonacci(num - 2);
else if(num <= 1) return num;
else return 1;
}
That's great, but because of the two recursive calls our stack grows very quickly and will take a long time for larger Fibonacci numbers.
Even for the 42nd Fibonacci it takes several seconds. Much larger than that and REPL will actually time out. Check it out: REPL
The question: Use memoization to improve the efficiency of this Fibonacci Sequence
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
In other words, we shall cache the results of our Fibonacci sequence as we find them. Rather than compute it each time, first we will check if we already have that Fibonacci number in our cache.
var fibonacciTable = [0, 1, 1]
function fibonacci(num){
if(num > 2){
if(!fibonacciTable[num-1]) fibonacciTable[num-1] = fibonacci(num-1);
if(!fibonacciTable[num-2]) fibonacciTable[num-2] = fibonacci(num-2);
return fibonacciTable[num-1] + fibonacciTable[num-2];
}
else if(num <= 1) return num;
else return 1;
}
fibonacci(1000) //returns 4.346655768693743e+208 almost instantly
Read more here Trasb.org