We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 0129ca4 + ac34d5d commit 6fafd55Copy full SHA for 6fafd55
Algorithms/dynamic_programming/fibonacci.js
@@ -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
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