Recursive Fibonacci in Javascript
Written by Tyler La Fronz on February 7, 2018
The Fundamentals
At its core, a basic Fibonacci algorithm is incredibly slow and inefficient. This implementation of Fibonacci includes a data structure to memorize previously calculated numbers in the sequence.
Please enter a value:
The function that computes this
var memo = [0, 1]; //Stores the previously calculated values
function fib(fibNum) {
var result = 0;
if (memo[fibNum]) { //Checks for previously calculated value
result = memo[fibNum]; //returns the value stored
} else if (fibNum >= 2) {
result = fib(fibNum - 1) + fib(fibNum - 2); //recursively calls for the value
memo[fibNum] = result; //Stores the result
}
return result; //returns the value
}