Greatest common divisor
Solutions
Solution 1 (Click to Show/Hide)
function gcd(a, b) {
// Recursive use of Euclidean algorithm
return b == 0 ? a : gcd(b, a % b);
}
This is an implementation of the Euclidean algorithm, which is used to compute the GCD of two numbers. In each instance of recursion, the original two numbers, a
and b
, are respectively replaced by b
and a % b
, which is the remainder of a/b
. This continues until the remainder is zero.