From 29d341cc8cc33c34828f5fb444950cf8dd2ee25c Mon Sep 17 00:00:00 2001 From: frankymacster Date: Tue, 17 Dec 2019 20:44:24 -0500 Subject: [PATCH] add Simple Recursion/Nth Factorial --- Simple Recursive/Nth Factorial/README.md | 9 ++++++ Simple Recursive/Nth Factorial/code.js | 41 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 Simple Recursive/Nth Factorial/README.md create mode 100644 Simple Recursive/Nth Factorial/code.js diff --git a/Simple Recursive/Nth Factorial/README.md b/Simple Recursive/Nth Factorial/README.md new file mode 100644 index 00000000..12672dd7 --- /dev/null +++ b/Simple Recursive/Nth Factorial/README.md @@ -0,0 +1,9 @@ +# nth Factorial +Finding nth Factorial using recursion. + +## Complexity +* **Time**: ![](https://latex.codecogs.com/svg.latex?O(2ⁿ)) +* **Space**: ![](https://latex.codecogs.com/svg.latex?O(2ⁿ)) + +## References +* [codeburst.io](https://codeburst.io/learn-and-understand-recursion-in-javascript-b588218e87ea) \ No newline at end of file diff --git a/Simple Recursive/Nth Factorial/code.js b/Simple Recursive/Nth Factorial/code.js new file mode 100644 index 00000000..46089fe1 --- /dev/null +++ b/Simple Recursive/Nth Factorial/code.js @@ -0,0 +1,41 @@ +// import visualization libraries { +const { Tracer, Array1DTracer, Layout, VerticalLayout } = require('algorithm-visualizer'); +// } + +// define tracer variables { +var tracer = new Array1DTracer('Sequence'); +Layout.setRoot(new VerticalLayout([tracer])); +var index = 15; +var D = [1]; +for (var i = 1; i < index; i++) { + D.push(0); +} +tracer.set(D); +Tracer.delay(); +// } + +function fact(num) { + if (num < 0) { + return; + } + + if (num === 0) { + return 1; + } + + var res = num * fact(num - 1); + + D[num - 1] = res; + + // visualize { + tracer.select(num - 1); + Tracer.delay(); + tracer.patch(num - 1, D[num - 1]); + Tracer.delay(); + tracer.depatch(num - 1); + tracer.deselect(num - 1); + // } + + return res; +} +fact(index); \ No newline at end of file