GCD of two numbers
The Greatest Common Divisor (GCD), or Highest Common Factor (HCF), is the largest number that divides two numbers without a remainder.
Calculating Greatest Common Divisors
A naive approach to this is to iterate from all numbers between 1 to and return the biggest number that divides them
int gcd(int m, int n) {
int maxDivisor = 1;
for (int i = 1; i < min(m,n); ++i) {
if(m%i == 0 && n%i ==0) {
maxDivisor = i;
}
}
return i;
}
To find the GCD of two numbers using recursion, we will be using the principle

Steps of the Algorithm
Check if
a==0
, if yes, returnb
.Check if
b==0
, if yes, returna
.Check if
a==b
, if yes, returna
.Check if
a>b
if yes, callGCD()
function using the argumentsa−b
andb
recursively, otherwise callGCD()
function using the argumentsa
and
Implementation
int gcd(int a , int b) {
if(a == 0) return b;
if(b == 0) return a;
return a > b ? gcd(a-b,b) : gcd(a,b-a);
}
Complexity Analysis
Time Complexity
In this algorithm, the number of steps are linear, for e.g. in which we will subtract from in each recursion, so the time complexity will be
Space Complexity
The space complexity here is because the space complexity in a recursive function is equal to the maximum depth of the call stack.
Last updated