Created
March 12, 2023 05:33
-
-
Save pjcodesjs/6e2991066214af878bc88ed04a2491ac to your computer and use it in GitHub Desktop.
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
// RECURSIVE APPROACH | |
function fibonacciRecursive(n) { | |
if (n <= 1) { | |
return n; | |
} else { | |
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); | |
} | |
} | |
console.log(fibonacciRecursive(7)); // Output: 13 | |
// ITERATIVE APPROACH | |
function fibonacciIterative(n) { | |
if (n <= 1) { | |
return n; | |
} | |
let fib = 1; | |
let prevFib = 1; | |
for (let i = 2; i < n; i++) { | |
let temp = fib; | |
fib += prevFib; | |
prevFib = temp; | |
} | |
return fib; | |
} | |
console.log(fibonacciIterative(7)); // Output: 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment