GCD of two numbers
Last updated
Last updated
The Greatest Common Divisor (GCD), or Highest Common Factor (HCF), is the largest number that divides two numbers without a remainder.
A naive approach to this is to iterate from all numbers between 1 to and return the biggest number that divides them
The GCD is always positive irrespective of the sign of the input numbers. If the given number is negative, we will simply ignore its -
sign using the abs()
function
To find the GCD of two numbers using recursion, we will be using the principle
Check if a==0
, if yes, return b
.
Check if b==0
, if yes, return a
.
Check if a==b
, if yes, return a
.
Check if a>b
if yes, call GCD()
function using the arguments a−b
and b
recursively, otherwise call GCD()
function using the arguments a
and
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
The space complexity here is because the space complexity in a recursive function is equal to the maximum depth of the call stack.