JS how to find the greatest common divisor

bboy picture bboy · Jul 3, 2013 · Viewed 58.2k times · Source

I would like to find the greatest common divisor using JavaScript.

Anyone done that before and willing to share?

Answer

alex picture alex · Jul 3, 2013

Here is a recursive solution.

 var gcd = function(a, b) {
  if (!b) {
    return a;
  }

  return gcd(b, a % b);
}

Our base case is when b is equal to 0. In this case, we return a.

When we're recursing, we swap the input arguments but we pass the remainder of a / b as the second argument.