DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

Find the Greatest Common Divisor

Write a function that takes two numbers and returns their greatest common divisor (GCD).

Solution

function findGCD(number1, number2) {
  if(number2 === 0) {
    return number1;
  }

  return findGCD(number2, number1 % number2);
}

console.log(findGCD(-1, -5));
console.log(findGCD(19, 5));
console.log(findGCD(72, 81));
console.log(findGCD(14, 0));
Enter fullscreen mode Exit fullscreen mode

Result

> -1
> 1
> 9
> 14
Enter fullscreen mode Exit fullscreen mode

Top comments (0)