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:
“One of the greatest faults of the women of the present time is a silly fear of things, and one object of the education of girls should be to give them knowledge of what things are really dangerous.”
—Ellen Henrietta Swallow Richards (18421911)
“But neither milk-white rose nor red
May bloom in prison air;
The shard, the pebble, and the flint,
Are what they give us there:
For flowers have been known to heal
A common mans despair.”
—Oscar Wilde (18541900)
