Professional Documents
Culture Documents
Functions can call other functions. In fact, a function can call itself, either directly or
indirectly. When a function calls itself it is known as recursion, a Computer Science
methodology which can be implemented with or without functions.
Many examples of the use of recursion may be found: the technique is useful both for the
definition of mathematical functions and for the definition of data structures. Naturally, if a
data structure may be defined recursively, it may be processed by a recursive function3.4.1
Recursive functions
Many mathematical functions can be defined recursively:
factorial
Fibonacci
Euclid's GCD (greatest common denominator)
Fourier Transform
Many problems can be solved recursively, eg games of all types from simple ones like the
Towers of Hanoi problem to complex ones like chess. In games, the recursive solutions are
particularly convenient because, having solved the problem by a series of recursive calls, you
want to find out how you got to the solution. By keeping track of the move chosen at any
point, the program call stack does this housekeeping for you! This is explained in more detail
later.
Note how this function calls itself to evaluate the next term. Eventually it will reach the
termination condition and exit. However, before it reaches the termination condition, it will
have pushed n stack frames onto the program's run-time stack.
The termination condition is obviously extremely important when dealing with recursive
functions. If it is omitted, then the function will continue to call itself until the program runs
out of stack space - usually with moderately unpleasant results!
Technically, a recursive function is a function that makes a call to itself. To prevent infinite
recursion, you need an if-else statement (of some sort) where one branch makes a recursive
call, and the other branch does not. The branch without a recursive call is usually the base
case (base cases do not make recursive calls to the function).
Tower of Hanoi
The objective of the puzzle is to move the entire stack to another rod, obeying the following
rules:
When my initial pile has one, two, or three rings you can probably work out hot to solve the
problem in each such case. But clearly the more rings there are the harder it gets to solve the
problem in each case. So what if I want to write a program which will work for any pile of
rings however large. We need an algorithm which will work for an arbitrarily large pile of
rings.
By means of mathematical induction, it is easily proven that the above procedure requires the
minimal number of moves possible, and that the produced solution is the only one with this
minimal number of moves. Using recurrence relations, the exact number of moves that this
solution requires can be calculated by: 2h − 1. This result is obtained by noting that steps 1
and 3 take Th − 1 moves, and step 2 takes one move, giving Th = 2Th − 1 + 1.