An algorithm to find the GCD of two numbers in javascript.
We will implement a simple algorithm with different approaches to find the gcd of two numbers in javascript. Everything will be written in ES6.
GCD: GCD of two numbers is the biggest number which divides both the given numbers.
Example
Input: 60 15 36 60 Output: 15 12
Iterative approach.
Implementation
- We will loop until both the given numbers are not eqaul.
- Then in each iteration we will check if
num1is greater thannum2or not. - If it is greater then we will subtract
num2fromnum1else we will subtractnum1fromnum2. - This approach is based on Euclidean Algorithm.
let gcd = (num1, num2) => {
//Loop till both numbers are not equal
while(num1 != num2){
//check if num1 > num2
if(num1 > num2){
//Subtract num2 from num1
num1 = num1 - num2;
}else{
//Subtract num1 from num2
num2 = num2 - num1;
}
}
return num2;
}
Input: console.log(gcd(60, 15)); console.log(gcd(60, 36)); Output: 15 12
Time complexity: O(log(a) + log(b)) = O(n).
Space complexity: O(1).
Time and Space complexity
- In each iteration we are reducing any one number by the other number, so Time complexity is O(log(a) + log(b)).
- We are using constant space, so Space complexity is O(1).
Recursive Approach
- We are going to implement the above approach with recursion.
- We are going to check if
num2is0then returnnum1. - Else call the same function recursively with
num2and remainder ofnum1 % num2.
let gcd = (num1, num2) => {
//if num2 is 0 return num1;
if(num2 === 0){
return num1;
}
//call the same function recursively
return gcd(num2, num1 % num2);
}
Input: console.log(gcd(60, 15)); console.log(gcd(36, 60)); Output: 15 12
Time complexity: O(n) or O(log(a) + log(b)).
Space complexity: O(m + n).
Time and Space complexity
- We are calling the same function recursively till the
num2is0and each callnum1andnum2a are getting reduced, so Time complexity is O(n) or O(log(x) + log(y)). - Each recursive function is stored in call stack and it is called until
num2is not0, so Space complexity is O(n + m).