UMBC CMSC202, Computer Science II, Fall 1998,
Sections 0101, 0102, 0103, 0104
12. Recursion, again
Tuesday October 13, 1998
Assigned Reading: none
Handouts (available on-line):
Programs from this lecture.
- The greatest common divisor (gcd) of two numbers m and n is the
largest integer that divides both m and n. We show how recursion is used
to find a fast algorithm to compute gcd.
- First, we implement a naive algorithm to compute the gcd of two
numbers. This program simply tries every number
between 2 and the smaller of m and n. The largest divisor is returned. The
sample run shows that this program is quite
slow. It took 22 seconds in one case to compute the gcd of two large-ish
- Euclid, an ancient Greek mathematician, showed that
gcd(m,n) = gcd(n, m % n).
Using Euclid's recursive algorithm, we can produce a faster program to compute the gcd of two numbers. The sample run shows a running time of less than 0.1
seconds for the same input that took 22 seconds previously. Note that the
worst case input to Euclid's gcd algorithm is two consecutive Fibonacci
- We can also implement Euclid's algorithm using a while loop instead of
recursion. (Program and sample run.) With modern optimizing compilers,
this program isn't necessarily faster than the recursive version. One
disadvantage of not using recursion is that Euclid's original formulation
- Another classic example of problem solving by recursion is the Towers
of Hanoi problem. Program and sample run. Again, the emphasis here is how
to think recursively. Unravelling the recursive calls for this problem
gets pretty confusing.
- Next, we look at an example of mutually recursion where two
functions call each other. In our program, the
function count_alpha() does not call itself directly, but does
call the function count_non_alphas(). Since
count_non_alphas() also calls count_alpha(), the
execution of count_alpha() does not return before another call to
count_alpha() is issued. Hence we must take great care to ensure
that the recursion terminates properly. In this program, we rely on the
null character at the end of the string to trigger the base case of the
recursion. See sample run.
- We went over a few questions on recursion from past exams.
29 Oct 1998 17:14:03 EST
to Fall 1998 CMSC 202 Section Homepage