Chapter 13: Problem 5
What is direct recursion? What is indirect recursion?
Short Answer
Expert verified
Answer: Direct recursion occurs when a function calls itself within its own body to solve a problem by breaking it down into smaller sub-problems. An example of direct recursion is the factorial function:
factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Indirect recursion occurs when a function calls another function, which might call the original function either directly or through a sequence of other functions, eventually leading back to the initial function. It involves multiple functions that call each other in a cycle. An example of indirect recursion is the following functions A and B:
function A(n):
if n <= 0:
return 1
else:
return n * B(n-1)
function B(n):
if n == 1:
return 1
else:
return n * A(n-1)