JavaScript Code to Perform GCD using Recursion

JavaScript Code to Perform GCD using Recursion

GCD, also known as Greatest Common Divisor, is the largest positive integer that divides two or more numbers without leaving any remainder. In order to find the GCD of two numbers using recursion, we need to understand the concept of recursion first. Recursion is a technique that allows a function to call itself in order to compute a result.

Recursive Solution

Let's see how we can find the GCD of two numbers using recursion in JavaScript. We will define a function called gcd that takes two parameters, a and b, and returns their GCD.

function gcd(a, b) {
  if (b == 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}

The function starts with checking if b equals to zero. If it is, then a is the GCD of a and b. If not, then we call the gcd function recursively with b and the remainder of a divided by b. This process continues until we get a remainder of zero, which means that we have found the GCD of a and b.

Iterative Solution

There is also an iterative solution to find the GCD of two numbers. In this solution, we use a loop instead of recursion.

function gcd(a, b) {
  while (b != 0) {
    var t = b;
    b = a % b;
    a = t;
  }
  return a;
}

The function starts with checking if b equals to zero. If it is, then a is the GCD of a and b. If not, we perform the following steps:

  1. We store the value of b in a temporary variable t.
  2. We update the value of b to be the remainder of a divided by b.
  3. We update the value of a to be the value of t, which is the previous value of b.
  4. The loop continues until b equals to zero.

At the end of the loop, we return the value of a, which is the GCD of a and b.

Conclusion

In conclusion, we can find the GCD of two numbers using recursion or iteration. Both solutions have their own advantages and disadvantages. Recursion can be more elegant and easier to understand for some people, while iteration can be more efficient and easier to implement for others. It's important to understand both solutions and choose the one that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe