From 6aaa663688bafd6626ea63243a77e9754b799c10 Mon Sep 17 00:00:00 2001 From: Lee Southerst Date: Thu, 28 Sep 2017 12:59:16 -0400 Subject: [PATCH 1/2] Added bottom up DP implementation of Fibonacci --- Algorithms/dynamic_programming/fibonacci.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Algorithms/dynamic_programming/fibonacci.js diff --git a/Algorithms/dynamic_programming/fibonacci.js b/Algorithms/dynamic_programming/fibonacci.js new file mode 100644 index 000000000..0595afead --- /dev/null +++ b/Algorithms/dynamic_programming/fibonacci.js @@ -0,0 +1,14 @@ + +function fib(n) { + var table = []; + table.push(1); + table.push(1); + for (var i = 2; i < n; ++i) { + table.push(table[i - 1] + table[i - 2]); + } + console.log("The %dth fibonacci number is %d", n, table[n - 1]); +} + +fib(200); +fib(5); +fib(10); From ac34d5d147883c2af553ebc92bf27b0c171492b5 Mon Sep 17 00:00:00 2001 From: Lee Southerst Date: Wed, 25 Oct 2017 10:30:43 -0400 Subject: [PATCH 2/2] Add comments --- Algorithms/dynamic_programming/fibonacci.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Algorithms/dynamic_programming/fibonacci.js b/Algorithms/dynamic_programming/fibonacci.js index 0595afead..273d9aac5 100644 --- a/Algorithms/dynamic_programming/fibonacci.js +++ b/Algorithms/dynamic_programming/fibonacci.js @@ -1,3 +1,12 @@ +// Calculates fib(n) such that fib(n) = fib(n - 1) + fib(n - 2) +// fib(0) = fib(1) = 1 +// Uses a bottom up dynamic programming approach +// Solve each subproblem once, using results of previous subproblems, +// which are n-1 and n-2 for Fibonacci numbers + +// Although this algorithm is linear in space and time as a function +// of the input value n, it is exponential in the size of n as +// a function of the number of input bits function fib(n) { var table = []; @@ -6,9 +15,11 @@ function fib(n) { for (var i = 2; i < n; ++i) { table.push(table[i - 1] + table[i - 2]); } - console.log("The %dth fibonacci number is %d", n, table[n - 1]); + console.log("Fibonacci #%d = %d", n, table[n - 1]); } +fib(1); +fib(2); fib(200); fib(5); fib(10);