-
Notifications
You must be signed in to change notification settings - Fork 43
/
fibonacci_dp.js
44 lines (39 loc) · 935 Bytes
/
fibonacci_dp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233...
let calculations = 0;
// Recursion version
function fibonacci(n) { //O(2^n)
if (n < 2) {
return n
}
return fibonacci(n-1) + fibonacci(n-2);
}
// DP version 1 (bottom down)
function fibonacciMaster() { //O(n)
let cache = {};
return function fib(n) {
calculations++;
if (n in cache) {
return cache[n];
} else {
if (n < 2) {
return n;
} else {
cache[n] = fib(n-1) + fib(n-2);
return cache[n];
}
}
}
}
// DP version 2 (bottom up)
function fibonacciMaster2(n) {
let answer = [0,1];
for ( let i = 2; i <= n; i++) {
answer.push(answer[i-2]+ answer[i-1]);
}
return answer.pop();
}
const fasterFib = fibonacciMaster();
console.log('Slow', fibonacci(35))
console.log('DP', fasterFib(100));
console.log('DP2', fibonacciMaster2(100));
console.log('we did ' + calculations + ' calculations');