chore(Javascript): add factorial recursion (#756)

pull/757/head
Valerio Cipolla 2022-05-06 14:01:10 +01:00 committed by GitHub
parent 6a64805e36
commit 0cc7c94675
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 0 deletions

View File

@ -40,3 +40,7 @@
## Maths
- [Fibonacci Series](src/maths/fibonacci-series.js)
## Recursion
- [Factorial](src/recursion/factorial.js)

View File

@ -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');

View File

@ -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