Search code examples
javascriptmathgreatest-common-divisor

JS how to find the greatest common divisor


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

Anyone done that before and willing to share?


Solution

  • Here is a recursive solution, using the Euclidean algorithm.

     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.