In this article, we will discuss a very popular algorithm that is generally used in interview coding questions. The aim is to find the greatest common divisor (GCD) between two numbers. The optimized algorithm is pretty fast as compared to the brute force approach.
The GCD of two integers (a, b), denoted by gcd(a,b)
, is defined as the largest positive integer d such that d | a and d | b where x | y implies that x divides y.
Example of GCD:
gcd(4, 8)
= 4gcd(10, 5)
= 5gcd(20,12)
= 4According to the Euclid’s Algorithm:
gcd(A,B) = gcd(B,A%B) // recurrence for GCD
gcd(A,0) = A // base case
Let’s discuss the proof of the recurrence.
Proof:
The GCD of more than 2 numbers, e.g., gcd(a,b,c)
is equal to gcd(a,gcd(b,c))
and so on.
int gcd(int a, int b) {return (b == 0 ? a : gcd(b, a % b));}int main() {// your code goes hereint a = 100, b = 20;int result;result = gcd(a,b);cout << result;}
Explanation:
gcd()
, accepts two numbers as input and provides the output. As we are using the %
operator, the number of recursive calls required to reach the final result would be less than n
where n
= max(a,b)
.