Discover how a function can call itself to solve a problem step by step!
Why Factorial Using Recursion in DSA Typescript?
Imagine you want to find the factorial of a number, like 5! (which means 5 x 4 x 3 x 2 x 1). Doing this by hand or writing many lines of code to multiply each number one by one can be tiring and error-prone.
Manually multiplying each number takes a lot of time and can easily lead to mistakes, especially for bigger numbers. Writing repetitive code for each step is boring and not practical.
Recursion lets the function call itself to solve smaller parts of the problem until it reaches the simplest case. This way, the factorial calculation becomes clean, short, and easy to understand.
function factorial(n: number): number {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}function factorial(n: number): number {
if (n === 0) return 1;
return n * factorial(n - 1);
}Recursion enables solving complex problems by breaking them into simpler, repeatable steps that call themselves.
Calculating combinations in probability, where factorials are used to find how many ways to choose items from a group.
Manual multiplication is slow and error-prone.
Recursion simplifies repetitive tasks by self-calling.
Factorial is a classic example to learn recursion.