Recursive Call - Recursive Programs - Recursive Procedures - Greatest Common Divisor

Greatest Common Divisor

The Euclidean algorithm, which computes the greatest common divisor of two integers, can be written recursively.

Function definition:

 \gcd(x,y) = \begin{cases} x & \mbox{if } y = 0 \\ \gcd(y, \operatorname{remainder}(x,y)) & \mbox{if } y > 0 \\ \end{cases}
Pseudocode (recursive):
function gcd is: input: integer x, integer y such that x >= y and y >= 0
1. if y is 0, return x 2. otherwise, return
end gcd

Recurrence relation for greatest common divisor, where expresses the remainder of :

Computing the recurrence relation for x = 27 and y = 9:
gcd(27, 9) = gcd(9, 27% 9) = gcd(9, 0) = 9
Computing the recurrence relation for x = 259 and y = 111:
gcd(259, 111) = gcd(111, 259% 111) = gcd(111, 37) = gcd(37, 0) = 37

The recursive program above is tail-recursive; it is equivalent to an iterative algorithm, and the computation shown above shows the steps of evaluation that would be performed by a language that eliminates tail calls. Below is a version of the same algorithm using explicit iteration, suitable for a language that does not eliminate tail calls. By maintaining its state entirely in the variables x and y and using a looping construct, the program avoids making recursive calls and growing the call stack.

Pseudocode (iterative):
function gcd is:
input: integer x, integer y such that x >= y and y >= 0
1. create new variable called remainder
2. begin loop 1. if y is zero, exit loop 2. set remainder to the remainder of x/y 3. set x to y 4. set y to remainder 5. repeat loop
3. return x
end gcd

The iterative algorithm requires a temporary variable, and even given knowledge of the Euclidean algorithm it is more difficult to understand the process by simple inspection, although the two algorithms are very similar in their steps.

Read more about this topic:  Recursive Call, Recursive Programs, Recursive Procedures

Famous quotes containing the words greatest and/or common:

    The highest proof of civility is that the whole public action of the State is directed on securing the greatest good of the greatest number.
    Ralph Waldo Emerson (1803–1882)

    All the philosophy, therefore, in the world, and all the religion, which is nothing but a species of philosophy, will never be able to carry us beyond the usual course of experience, or give us measures of conduct and behaviour different from those which are furnished by reflections on common life. No new fact can ever be inferred from the religious hypothesis; no event foreseen or foretold; no reward or punishment expected or dreaded, beyond what is already known by practice and observation.
    David Hume (1711–1776)