0
0
DSA Typescriptprogramming~3 mins

Why Fibonacci Using Recursion in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if a simple function could magically solve a big problem by calling itself again and again?

The Scenario

Imagine you want to find the 10th number in the Fibonacci sequence by writing down each number one by one on paper.

You start adding the last two numbers repeatedly to get the next one.

The Problem

This manual way is slow and tiring because you have to remember all previous numbers and add them again and again.

It's easy to make mistakes or lose track, especially for bigger numbers.

The Solution

Using recursion, the computer can solve this by breaking the problem into smaller parts.

It calls itself to find the smaller Fibonacci numbers and then adds them up automatically.

This saves you from doing all the repeated work manually.

Before vs After
Before
let fib = [0, 1];
for (let i = 2; i <= 10; i++) {
  fib[i] = fib[i-1] + fib[i-2];
}
console.log(fib[10]);
After
function fibonacci(n: number): number {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(10));
What It Enables

Recursion lets us solve complex problems by breaking them into simpler, repeatable steps that the computer handles for us.

Real Life Example

Calculating Fibonacci numbers helps in computer graphics, financial models, and nature simulations where patterns repeat in a similar way.

Key Takeaways

Manual addition for Fibonacci is slow and error-prone.

Recursion breaks the problem into smaller calls automatically.

This makes code simpler and easier to understand for repeated patterns.