Greatest Common Divisor
The Euclidean algorithm, which computes the greatest common divisor of two integers, can be written recursively.
Function definition:
| 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 love is a mothers;
Then comes a dogs,
Then comes a sweethearts.”
—(20th century)
“Friendless. Having no favors to bestow. Destitute of fortune. Addicted to utterance of truth and common sense.”
—Ambrose Bierce (18421914)
