Next: GCD: problems of the Up: Unit 06 Previous: Example: computing the greatest

## GCD: by directly exploiting the definition

• We are looking for the maximum divisor of both x and y.
• Observation: 1 < = gcd(x, y) < = min(x, y)
Hence, it is sufficient to try out the numbers between 1 and min(x, y).
• It is better to start from min(x, y) and go down toward 1. As soon as we find a common divisor of x and y, we can immediately return it.

First refinement of the algorithm:

public static int greatestCommonDivisor(int x, int y) {
int gcd;

initialize gcd to the minimum of x and y
while ((gcd > 1) && (we have not found a common divisor))
if (gcd divides both x and y)
we have found a common divisor
else
gcd-;

return gcd;
}

Observations:

• The loop always terminates because at each iteration
• either we find a divisor,
• or we decrement gcd by 1 (at most we arrive at 1).

• To check whether we have found the gcd we make use of a boolean variable (used in the loop condition).
• To verify whether x (or y) divides gcd we use the "%" operator.

Next: GCD: problems of the Up: Unit 06 Previous: Example: computing the greatest