Print out the n-th entry in the fibonacci series. The fibonacci series is an ordering of numbers where each number is the sum of the preceeding two.
For example, the sequence
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
forms the first ten entries of the fibonacci series.
fib(4) === 3
Two solutions:
Iteractive
Recusive
function fib(n) {
let num = 0;
let arr = [0, 1]; // manual add
for (let i=2; i<=n; i++){ // start at 2
num = arr[i-2] + arr[i-1];
arr.push(num);
}
return arr[n];
}
function fib(n){
if (n <= 1){
return n;
}
return fib(n-1) + fib(n-2);
}
function memoize(fn){
const cache = {};
return function(...args){
if (cache[args]){ // had called
return cache[args];
}
const result = fn.apply(this, args);
cache[args] = result;
return result;
};
}
function slowFib(n){
if (n <= 1){
return n;
}
return fib(n-1) + fib(n-2); // make sure we call the right function
}
fib = memoize(slowFib);
// const fib = memoize(slowFib);
fib(4)