Skip to content

Instantly share code, notes, and snippets.

@obrenoco
Last active January 10, 2022 01:55
Show Gist options
  • Save obrenoco/c300e132095f7c87bc1fa0ce52d9feeb to your computer and use it in GitHub Desktop.
Save obrenoco/c300e132095f7c87bc1fa0ce52d9feeb to your computer and use it in GitHub Desktop.
Fibonacci
// using phi - best performance
// see: https://akuli.github.io/math-tutorial/fib.html
function fibonacciGoldenRation(n: number) {
const phi = (1 + Math.sqrt(5))/2;
const asymptotic = Math.pow(phi, n) / Math.sqrt(5);
return Math.round(asymptotic);
}
// using for() loop
const fibonacciForLoop = (num: number) => {
var sequence = [0, 1];
for (let position = 2; position < num + 1; position++) {
sequence[position] = sequence[position - 1] + sequence[position - 2];
}
return sequence[num];
};
// using recursion - very poor performance
// just (console.log(num) and you'll see why)
const fibonacciRecursive = (num: number): number => {
if (num === 0) return 0;
if (num <= 2) return 1;
return fibonacciRecursive(num - 1) + fibonacciRecursive(num - 2);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment