JS Factorial using recursion

지원 ·2023년 5월 8일
0

Factorial Iteratively (non recursive)

Example of what factorial is

4! = 4 x 3 x 2 x 1;

function factorial(num) {
	let total = 1;
    for (let i = num; i > 1; i--) {
		total = total * 1
    }
    return total
}

factorial(4) // 4 * 3 * 2 * 1 = 24 

Factorial Recursively

function factorial(num) {
	
	return num * factorial(num - 1); 
}

factorial(4) // 4 * 3 * 2 * 1 = 24 

Breaking down the factorial recursively

return num * factorial(num - 1);
if num is 5 --> 5 x 4 x 3 x 2 x 1 x 0 x -1 x -2 x -3
With just that, num becomes an infinite loop.
You need an ENDPOINT (Base case)

Base case added to avoid "Maximum call stack size exceeded'

  • need base case
  • need return statement
  • if no basecase, Stack overflow occurs
function factorial(num) {
	if(num === 1) return 1; 
	return num * factorial(num - 1); 
}

factorial(4) // 4 * 3 * 2 * 1 = 24 
factorial(5) // 5 * 4 * 3 * 2 * 1 = 120 

0개의 댓글