Properties of recursive algorithms

Now, the question can be, "If a function calls itself, then how does it stop or know when to finish the recursive call?" When we are writing a recursive solution, we have to make sure it has the following properties:

  1. Each recursive call should be on a smaller subproblem. Like the factorial example, a factorial of 6 is solved with 6 and multiplication of a factorial of 5 and so it goes on.
  2. It must have a base case. When the base case is reached, there will be no further recursion, and the base case must be able to solve the problem without any further recursive call. In our factorial example, we did not go any further down from 0. So, in this case, 0 is our base case.
  3. There should not be any cycle. If each recursive call makes a call to the same problem, then there will be a never-ending cycle. After some repetitions, the computer will show a stack overflow error.

So, if we now write our factorial program using PHP 7, then it will look like this:

function factorial(int $n): int {
if ($n == 0)
return 1;

return $n * factorial($n - 1);
}

In the preceding example code, we can see that we have a base condition where we are returning 1 when the value of $n is 0. If this condition is not met, then we are returning a multiplication of $n and a factorial of $n-1. So, it satisfies property to both numbers, 1 and 3. We are avoiding cycles and also making sure each recursive call is creating a subproblem of the bigger one. We will write the recursive behavior like this algorithm:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset