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 GCD(a,b)=GCD(a,b−a)
Steps of the Algorithm
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
Implementation
Complexity Analysis
Time Complexity
O(max(a,b)) In this algorithm, the number of steps are linear, for e.g. GCD(x,1) in which we will subtract 1 from x in each recursion, so the time complexity will be O(max(a,b))
Space Complexity
The space complexity here is O(max(a,b)) because the space complexity in a recursive function is equal to the maximum depth of the call stack.