Drill

ProblemsJavaScript › warmup

Greatest common divisor

easywarmupJavaScript

Reducing a fraction, or laying tiles that divide a wall evenly, both come down to the same number.

greatestCommonDivisor(first: int, second: int) → int

Solve it in the editor →

Where you start

function greatestCommonDivisor(first, second) {
  
}

Worked examples

CallResult
greatestCommonDivisor(12, 18)6
greatestCommonDivisor(17, 5)1
greatestCommonDivisor(0, 5)5
greatestCommonDivisor(0, 0)0

Hint

Euclid: keep replacing the pair with (second, first mod second) until the second is zero.

Reference solution in JavaScript
function greatestCommonDivisor(first, second) {
  let a = Math.abs(first), b = Math.abs(second);
  while (b !== 0) [a, b] = [b, a % b];
  return a;
}

The same problem in another language

More warmup problems in JavaScript