Comments

Notes

MCS 211

18 topics

Solving Recurences

Updated Feb 09, 20251 min read

A recursive algorithm is an algorithm that solves a problem by reducing it to smaller instances of the same problem. Instead of iterating through a sequence of operations, a recursive algorithm calls itself with a modified parameter until it reaches a condition that can be solved directly (known as the base case). Once the base case is reached, the algorithm begins to return results back through the chain of recursive calls.

There are 2 components that play vital role to solve problem by Recursion.

Base Condition:

The condition under which the recursive calls stop. It provides a simple, non-recursive solution that terminates the recursion.

Recursive Step:

The part of the algorithm where the problem is divided into one or more smaller subproblems. The algorithm calls itself to solve these subproblems.

Example: Factorial Function

Algorithm

​int factorial(int n)

1: 𝑖𝑓 𝑛 == 0 𝑡ℎ𝑒𝑛

2: 𝑟𝑒𝑡𝑢𝑟𝑛 1

3: 𝑒𝑙𝑠𝑒

4: 𝑟𝑒𝑡𝑢𝑟𝑛 𝑛 ∗ (𝑛 − 1)

5: endif

Mathematical Representation


factorial(n)={1if n=0n∗factorial(n−1)if n>0factorial(n) = \begin{cases} 1 &\text{if } n=0 \\ n * factorial(n-1) &\text{if } n >0\end{cases}factorial(n)={1n∗factorial(n−1)​if n=0if n>0​​


Pseudo Code

​function factorial(n):
if n == 0:
return 1 // Base case
else:
return n * factorial(n - 1) // Recursive case
Share