JS how to find the greatest common divisor

JavascriptMathGreatest Common-Divisor

Javascript Problem Overview


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

Anyone done that before and willing to share?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Taken from Wikipedia.

Recursive:

function gcd_rec(a, b) {
    if (b) {
        return gcd_rec(b, a % b);
    } else {
        return Math.abs(a);
    }
}

Iterative:

function gcd(a,b) {
    a = Math.abs(a);
    b = Math.abs(b);
    if (b > a) {var temp = a; a = b; b = temp;}
    while (true) {
        if (b == 0) return a;
        a %= b;
        if (a == 0) return b;
        b %= a;
    }
}
  • EDITed per user's comment

Solution 3 - Javascript

function egcd(a, b) {
    if (a == 0)
        return b;

    while (b != 0) {
        if (a > b)
            a = a - b;
        else
            b = b - a;
    }

    return a;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbboyView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - JavascriptYannisView Answer on Stackoverflow
Solution 3 - JavascriptAmaniView Answer on Stackoverflow