Skip to content

Commit 6fafd55

Browse files
authored
Merge pull request TheAlgorithms#16 from EternalEnvy/add-fibonacci
Added bottom up DP implementation of Fibonacci
2 parents 0129ca4 + ac34d5d commit 6fafd55

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Calculates fib(n) such that fib(n) = fib(n - 1) + fib(n - 2)
2+
// fib(0) = fib(1) = 1
3+
// Uses a bottom up dynamic programming approach
4+
// Solve each subproblem once, using results of previous subproblems,
5+
// which are n-1 and n-2 for Fibonacci numbers
6+
7+
// Although this algorithm is linear in space and time as a function
8+
// of the input value n, it is exponential in the size of n as
9+
// a function of the number of input bits
10+
11+
function fib(n) {
12+
var table = [];
13+
table.push(1);
14+
table.push(1);
15+
for (var i = 2; i < n; ++i) {
16+
table.push(table[i - 1] + table[i - 2]);
17+
}
18+
console.log("Fibonacci #%d = %d", n, table[n - 1]);
19+
}
20+
21+
fib(1);
22+
fib(2);
23+
fib(200);
24+
fib(5);
25+
fib(10);

0 commit comments

Comments
 (0)