Created
October 2, 2020 18:49
-
-
Save tudorilisoi/2f5b570d66074358b0fef722c35107aa 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
let i = 1 //step | |
//this implementation computes the sequence as an array | |
function fib(n) { | |
if (n === 1) { | |
return [1, 1] | |
} | |
const prev = fib(n - 1) | |
const rl = prev.length | |
const part = prev[rl - 1] + prev[rl - 2] | |
console.log(`prev:`, prev) | |
console.log(`part:`, part) | |
return [...prev, part] | |
} | |
// console.log(fib(1)) | |
// console.log(fib(5)) | |
//this implementation computes the sum as an integer | |
const fibonacci = (num) => { | |
console.log(`step ${i++}`) | |
console.log(`doing fib(${num})`) | |
if (num <= 1) { return num } | |
return fibonacci(num - 2) + fibonacci(num - 1) | |
} | |
console.log(fibonacci(7)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment