...

/

Solution Review: Find the Greatest Common Divisor

Solution Review: Find the Greatest Common Divisor

This review provides a detailed analysis of the solution to find the greatest common divisor.

Solution: Using Recursion

Press + to interact
function gcd(testVariable1, testVariable2) {
// Base case
if (testVariable1 == testVariable2) {
return testVariable1;
}
// Recursive case
if (testVariable1 > testVariable2) {
return gcd(testVariable1 - testVariable2, testVariable2);
}
else {
return gcd(testVariable1, testVariable2 - testVariable1);
}
}
// Driver Code
var number1 = 6;
var number2 = 9;
console.log(gcd(number1, number2));

Explanation

The naive approach to finding GCDGCD of 22 numbers is to list all their divisors. Then pick the common divisors, and then select the greatest out of them.

However, an easy mathematical simplification can make our task easier.

The idea behind calculating GCDGCD is: If m>nm>n, GCD(m,n)GCD(m,n) is the same as ...

Access this course and 1400+ top-rated courses and projects.