Docsity

Understanding Recursion: A Programming Technique and Algorithm for Solving Problems, Slides of Computer Science

Partial preview of the text

Download Understanding Recursion: A Programming Technique and Algorithm for Solving Problems and more Slides Computer Science in PDF only on Docsity!

Recursive Algorithms

Answer: Answer:

Recursion

  • Recursion is more than just a programming technique. It has two other uses in computer science and software engineering, namely:
  • as a way of describing, defining, or specifying things.
  • as a way of designing solutions to problems (divide and conquer).

Iterative Definition

  • In general, we can define the factorial function in the following way:

Iterative Definition

  • This is an iterative definition of the factorial function.
  • It is iterative because the definition only contains the algorithm parameters and not the algorithm itself.
  • This will be easier to see after defining the recursive implementation.

Iterative vs. Recursive

  • Iterative 1 if n= factorial(n) = n x (n-1) x (n-2) x … x 2 x 1 if n>
  • Recursive

factorial(n) = 1 if n= n x factorial(n-1) if n>

Function calls itself

Function does NOT calls itself

Breakdown

  • Here, we see that we start at the top level, factorial(3), and simplify the problem into 3 x factorial(2).
  • Now, we have a slightly less complicated problem in factorial(2), and we simplify this problem into 2 x factorial(1). Docsity.com

Breakdown

  • We continue this process until we are able to reach a problem that has a known solution.
  • In this case, that known solution is factorial(0) = 1.
  • The functions then return in reverse order to complete the solution.

Breakdown

  • The other parts of the algorithm, excluding the base case, are known as the general case.
  • For example: 3 x factorial(2)  general case 2 x factorial(1)  general case etc …

Breakdown

  • After looking at both iterative and recursive methods, it appears that the recursive method is much longer and more difficult.
  • If that’s the case, then why would we ever use recursion?
  • It turns out that recursive techniques, although more complicated to solve by hand, are very simple and elegant to implement in a computer. Docsity.com

Iterative Algorithm

factorial(n) {

i = 1 factN = 1 loop (i <= n) factN = factN * i i = i + 1 end loop return factN

}

The iterative solution is very straightforward. We simply loop through all the integers between 1 and n and multiply them together.

Recursive Algorithm

factorial(n) {

if (n = 0) return 1 else return n*factorial(n-1) end if

}

Note how much simpler the code for the recursive version of the algorithm is as compared with the iterative version 

we have eliminated the loop and implemented the algorithm with 1 ‘if’ statement. Docsity.com