Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Created July 6, 2021 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/97883f116840c4341f686067f03a5175 to your computer and use it in GitHub Desktop.
Save danny-andrews/97883f116840c4341f686067f03a5175 to your computer and use it in GitHub Desktop.
Recursion example
// 4! = 4 * 3 * 2 * 1
// 5! = 5 * 4 * 3 * 2 * 1
// 1! = 1
// 0! = 1
const factorial = (num) => {
let total = 1;
for(let i = 1; i <= num; i++) {
total *= i;
}
return total;
}
const factorialRec = (num) => {
if(num === 1 || num === 0) return 1;
return num * factorialRec(num - 1);
};
// 5 * factorialRec(4)
// 5 * 4 * factorialRec(3)
// 5 * 4 * 3 * factorialRec(2)
// 5 * 4 * 3 * 2 * factorialRec(1)
// 5 * 4 * 3 * 2 * 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment