From df8a479ba00d71363d074891d1dc593c679dc68c Mon Sep 17 00:00:00 2001 From: TaHaSyedKhan Date: Fri, 17 Mar 2023 04:26:19 +0530 Subject: [PATCH] dynamic programming approach of fibonacci series --- algorithms/JavaScript/src/index.js | 2 ++ .../src/maths/dynamic-fibonacci-series.js | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 algorithms/JavaScript/src/maths/dynamic-fibonacci-series.js diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index 5264890b..3f4eaefa 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -7,6 +7,8 @@ require('./linked-lists/singly'); // Maths require('./maths/fibonacci-series'); +require('./maths/dynamic-fibonacci-series'); + // Recursion require('./recursion/factorial'); diff --git a/algorithms/JavaScript/src/maths/dynamic-fibonacci-series.js b/algorithms/JavaScript/src/maths/dynamic-fibonacci-series.js new file mode 100644 index 00000000..67d15b68 --- /dev/null +++ b/algorithms/JavaScript/src/maths/dynamic-fibonacci-series.js @@ -0,0 +1,30 @@ +// dynamic programming approach of fibonacci series +// time complexity: O(n) + +function dynamicFibonacci() { + let cache = {}; + + // here is the concept of closure in javaScript + const fib = (n) => { + // check if already calculated for n + if (n in cache) { + return cache[n]; + } else if (n < 2) { // base case + return n; + } else { + // store result in cache + cache[n] = fib(n - 1) + fib(n - 2); + return cache[n]; + } + } + console.log(fib(10)); +} +dynamicFibonacci(); +// output: 55 + + + + + + +