Calculate fibonacci numbers
// Calculate fibonacci numbers
let fibRec = (n) => {
if (n<=1) return n;
return fibRec(n-1) + fibRec(n-2);
}
let mem = [0, 1];
let fibMem = (n) => {
if (n<=1) return n;
if (!mem[n]) mem[n] = fibMem(n-1) + fibMem(n-2);
return mem[n];
}
fibBine = (n) => {
let l = (1 + Math.sqrt(5)) / 2;
let r = (1 - Math.sqrt(5)) / 2;
return Math.round((Math.pow(l, n) - Math.pow(r, n))/Math.sqrt(5));
}
let logWithTimer = (func, ...rest) => {
let start = Date.now();
let res = func.call(null, ...rest);
console.log("Res: " + res + "; Time: " + (Date.now() - start));
}
let n = 40
logWithTimer(fibRec, n); // 102334155, time 2975 ms
logWithTimer(fibMem, n); // 102334155, time 0 ms
logWithTimer(fibBine, n); // 102334155, time 0 ms