Last active
January 28, 2018 14:16
-
-
Save vadimkorr/ddd332fdc5ec9b1a0ff7706854b5e83f to your computer and use it in GitHub Desktop.
Calculate fibonacci numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment