From 0cc7c9467587141fd613b6263280283b5d21e09a Mon Sep 17 00:00:00 2001 From: Valerio Cipolla <83750862+ValerioCipolla@users.noreply.github.com> Date: Fri, 6 May 2022 14:01:10 +0100 Subject: [PATCH] chore(Javascript): add factorial recursion (#756) --- algorithms/JavaScript/README.md | 4 ++++ algorithms/JavaScript/src/index.js | 3 +++ .../JavaScript/src/recursion/factorial.js | 17 +++++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 algorithms/JavaScript/src/recursion/factorial.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 132fc3b0..f20b4faa 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -40,3 +40,7 @@ ## Maths - [Fibonacci Series](src/maths/fibonacci-series.js) + +## Recursion + +- [Factorial](src/recursion/factorial.js) diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index 806026de..b15a3328 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -7,6 +7,9 @@ require('./linked-lists/singly'); // Maths require('./maths/fibonacci-series'); +// Recursion +require('./recursion/factorial'); + // Searching require('./searching/binary-search-recursive'); require('./searching/binary-search'); diff --git a/algorithms/JavaScript/src/recursion/factorial.js b/algorithms/JavaScript/src/recursion/factorial.js new file mode 100644 index 00000000..e3065f29 --- /dev/null +++ b/algorithms/JavaScript/src/recursion/factorial.js @@ -0,0 +1,17 @@ +// algorithm to calculate factorial of positive integer n +// Time complexity: O(n) + +function factorial(n) { + // Error handling + // if n is negative or not an integer return string with error message + if (n < 0) return 'Only positive numbers allowed'; + if (!Number.isInteger(n)) return 'Only integers allowed'; + // if n is a positive integer + // base case: we reach 0, return 1 + if (n === 0) return 1; + // until we reach 0 we keep multiplying n by the factorial of n - 1 + return n * factorial(n - 1); +} + +console.log(factorial(5)); +// output: 120