Euclidean Algorithm
March 15 2025•Steve Boby George
“The School of Athens” by Raphael, via Wikimedia Commons
The algorithm states that the greatest common divisor (GCD) of two numbers can be derived using the following identity:
where
The difference is always divisible by the GCD, i.e.,
Example: GCD for and
Hence, the GCD of and is 1.
Optimization with Modulus
Instead of repeated subtraction, we can use the modulus operator:
The code for the algorithm can be written as follows:
class Solution {
public int GCD(int n1, int n2) {
while (n1 != 0 && n2 != 0) {
if (n1 > n2)
n1 = n1 % n2;
else
n2 = n2 % n1;
}
return (n2 == 0) ? n1 : n2;
}
}
Complexity Analysis
Time Complexity:
where and are given numbers. Because in every iteration, the algorithm is dividing the larger number with the smaller number, resulting in logarithmic time complexity.
Space Complexity:
Since only a couple of variables are used, i.e., constant space.