Skip to content

Instantly share code, notes, and snippets.

@shubich
Created January 16, 2018 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubich/11b42a131e2556a06ebb3748d80698b0 to your computer and use it in GitHub Desktop.
Save shubich/11b42a131e2556a06ebb3748d80698b0 to your computer and use it in GitHub Desktop.
Fibonacci algorithms
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);
}
@shubich
Copy link
Author

shubich commented Jan 16, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment