# Fibonacci

## Setup

const fib = (n) => {
if (n <= 2) {
result = 1;
} else {
result = fib(n-1) + fib(n-2);
}
return result;
};

const memo = [];

const fib2 = (n, memo = []) => {
if (memo[n]) {
return memo[n];
}

let result;
if (n <= 2) {
result = 1;
} else {
result = fib2(n - 1, memo) + fib2(n - 2, memo);
}

memo[n] = result;
return result;
};

const fib3 = (n) => {
const memo = [0, 1, 1]; // Initialize memo with base cases

for (let i = 3; i <= n; i++) {
memo[i] = memo[i - 1] + memo[i - 2];
}

return memo[n];
};

const fib4 = (n) => {
let a = 0, b = 1, c;
if (n < 3) {
if (n < 0) return fib(-n);
if (n === 0) return 0;
return 1;
}
while (--n)
c = a + b, a = b, b = c;
return c;
}

const fib5 = (n) => {

var i;
var resultsArray = [];

for (i = 0; i <= n; i++) {
if (i === 0) {
resultsArray.push(0);
} else if (i === 1) {
resultsArray.push(1);
} else {
resultsArray.push(resultsArray[i - 2] + resultsArray[i - 1]);
}
}

return resultsArray[n];
}

Testing in
TestOps/sec
Fib (Naive)
fib(20)
Better Fib
fib2(20)