I would like to find the greatest common divisor using JavaScript.
Anyone done that before and willing to share?
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.