Junior — Middle
Can you give an example of an algorithm or a task where a recursive approach is used?
sobes.tech AI
Answer from AI
An example of a classic problem where a recursive approach is used is calculating the factorial of a number.
Factorial n (denoted as n!) is the product of all natural numbers from 1 to n.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Will output 120
Another example is traversing a tree or data structure, such as walking through a filesystem, calculating Fibonacci numbers, solving partitioning problems, etc. Recursion is convenient when the problem naturally decomposes into subproblems of the same type.