Published Nov 06, 2021
[
 
]
Write a function fib(n)
that takes in a number as an argument. The function should return the n-th number of the
Fibonacci sequence
The 1st and 2nd number of the sequence is 1. To generate the next number of the sequence, we sum the previous two
n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|
fib(n) | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 24 |
/**
* This is the raw implementation of fib
* we have base cases
* we reduce the problem to sub-problem & following the definition
*
* @param n nth fib key
* @returns {number|*} the value
*/
const fibRaw = n => {
if (n <= 2) return 1;
return fibRaw(n - 1) + fibRaw(n - 2)
}
const fibMemo = (n, memo = {}) => {
if(n in memo) return memo[n]
if(n <= 2) return 1
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo)
return memo[n]
}
const fibTab = (n) => {
const table = Array(n + 1).fill(0)
table[1] = 1;
// each fib number contributes to next 2
for(let i = 0; i <= n; i++) {
table[i + 1] += table[i]
table[i + 2] += table[i]
}
return table[n]
}
O(n)
O(n)