0
0
DSA Typescriptprogramming~3 mins

Why Factorial Using Recursion in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

Discover how a function can call itself to solve a problem step by step!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function factorial(n: number): number {
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}
After
function factorial(n: number): number {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}
What It Enables

Recursion enables solving complex problems by breaking them into simpler, repeatable steps that call themselves.

Real Life Example

Calculating combinations in probability, where factorials are used to find how many ways to choose items from a group.

Key Takeaways

Manual multiplication is slow and error-prone.

Recursion simplifies repetitive tasks by self-calling.

Factorial is a classic example to learn recursion.