Last active
January 10, 2022 01:55
-
-
Save obrenoco/c300e132095f7c87bc1fa0ce52d9feeb to your computer and use it in GitHub Desktop.
Fibonacci
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
// 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