Created
January 16, 2018 14:39
-
-
Save shubich/11b42a131e2556a06ebb3748d80698b0 to your computer and use it in GitHub Desktop.
Fibonacci algorithms
This file contains hidden or 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
function fiboLoop(num) { | |
let a = 1, | |
b = 0, | |
temp; | |
while (num >= 1) { | |
temp = a; | |
a += b; | |
b = temp; | |
num--; | |
} | |
return b; | |
} | |
function fiboRec(num) { | |
if (num <= 2) return 1; | |
return fiboRec(num - 1) + fiboRec(num - 2); | |
} | |
function fiboMemo(num, memo) { | |
memo = memo || {}; | |
if (memo[num]) return memo[num]; | |
if (num <= 2) return 1; | |
return memo[num] = fiboMemo(num - 1, memo) + fiboMemo(num - 2, memo); | |
} | |
function fiboFormula(n) { | |
const Phi = (1 + Math.sqrt(5)) / 2; | |
const phi = (1 - Math.sqrt(5)) / 2; | |
const result = (Math.pow(Phi, n) - Math.pow(phi, n)) / Math.sqrt(5); | |
return Math.round(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jsPerf demo