Euclidβs algorithm for finding the Greatest Common Divisor of two or more integers is based on the following observations:
- if
then
- if
then
proof: suppose that
But then
Therefore
int gcd(int x, int y) {
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
Using the remainder operator instead of multiple subtraction operations is an improvement in performance however eventually one of
int gcd(int x, int y) {
while (x != 0 && y != 0) {
if (x > y) {
x %= y;
} else {
y %= x;
}
}
return max(x, y);
}
By ensuring that if
statement inside the while
loop
int gcd(int x, int y) {
if (x < y) {
swap(x, y);
}
while (y != 0) {
int remainder = x % y;
x = y;
y = remainder;
}
// at this point `gcd(x, y) = gcd(x, 0) = x`
return x;
}
However if
int gcd(int x, int y) {
while (y != 0) {
int remainder = x % y;
x = y;
y = remainder;
}
// at this point `gcd(x, y) = gcd(x, 0) = x`
return x;
}
Example: finding the GCD of
The last non-zero remainder is
Implementation
Recursive version
int gcd(int x, int y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}