find the greatest common divisor of two numbers in javascript

Here's one approach to finding the greatest common divisor of two positive integers using a recursive function:

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

// example usage:
console.log(gcd(12, 18)); // Output: 6
153 chars
11 lines

In this function, a and b are the two numbers for which we want to find the greatest common divisor. If b is 0, then we know that a is the greatest common divisor, so we return a. Otherwise, we use the modulo operator (%) to get the remainder when a is divided by b and recursively call the gcd function with b and the remainder as arguments.

This algorithm is based on the fact that the greatest common divisor of two numbers is the same as the greatest common divisor of one of the numbers and the remainder of the other number divided by the first number (i.e., gcd(a, b) = gcd(b, a % b)).

gistlibby LogSnag