Data Structures (BCA) 3rd Sem Previous Year Solved Question Paper 2022

Practice Mode:
2.

Write and analyze recursive algorithm to find the factorial of a number.

Explanation

Recursive algorithm to find the factorial of a number:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)



Analysis:

  1. Base Case: The base case in this algorithm is when n equals 0. In this case, the factorial is defined as 1, so the function returns 1.

  2. Recursive Case: If n is not 0, the function recursively calls itself with n - 1. The result of the recursive call is then multiplied by n. This recursive step breaks down the problem into smaller subproblems until it reaches the base case.

  3. Time Complexity: The time complexity of this algorithm is O(n), where 'n' is the input number. This is because, in the worst case, the function makes 'n' recursive calls before reaching the base case.

  4. Space Complexity: The space complexity is O(n) as well because each recursive call creates a new stack frame, and in the worst case, there will be 'n' stack frames in memory.

  5. Efficiency: While this recursive approach is easy to understand, it's not the most efficient way to calculate factorials, especially for large numbers, due to the high stack space usage. An iterative approach using a loop would be more efficient in practice.

example of a factorial calculation using the recursive algorithm:



factorial(5) = 5 * factorial(4)

= 5 * (4 * factorial(3))

= 5 * (4 * (3 * factorial(2)))

= 5 * (4 * (3 * (2 * factorial(1))))

= 5 * (4 * (3 * (2 * (1 * factorial(0)))))

= 5 * (4 * (3 * (2 * (1 * 1))))

= 5 * (4 * (3 * (2 * 1)))

= 5 * (4 * (3 * 2))

= 5 * (4 * 6)

= 5 * 24

= 120