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 greatest obstacle to being heroic is the doubt whether one may not be going to prove one’s self a fool; the truest heroism is to resist the doubt; and the profoundest wisdom, to know when it ought to be resisted, and when it be obeyed.
    Nathaniel Hawthorne (1804–1864)

    The propensity to truck, barter and exchange one thing for another ... is common to all men, and to be found in no other race of animals.
    Adam Smith (1723–1790)