Solution Review: Find the Greatest Common Divisor
This review provides a detailed analysis of the solution to find the greatest common divisor.
We'll cover the following...
Solution: Using Recursion
Press + to interact
function gcd(testVariable1, testVariable2) {// Base caseif (testVariable1 == testVariable2) {return testVariable1;}// Recursive caseif (testVariable1 > testVariable2) {return gcd(testVariable1 - testVariable2, testVariable2);}else {return gcd(testVariable1, testVariable2 - testVariable1);}}// Driver Codevar number1 = 6;var number2 = 9;console.log(gcd(number1, number2));
Explanation
The naive approach to finding of 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 is: If , is the same as ...
Access this course and 1400+ top-rated courses and projects.