Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  114] [ 3]  / answers: 1 / hits: 77959  / 11 Years ago, wed, july 3, 2013, 12:00:00

I would like to find the greatest common divisor using JavaScript.



Anyone done that before and willing to share?


More From » math

 Answers
6

Here is a recursive solution, using the Euclidean algorithm.


 var gcd = function(a, b) {
if (!b) {
return a;
}

return gcd(b, a % b);
}

Our base case is when b is equal to 0. In this case, we return a.


When we're recursing, we swap the input arguments but we pass the remainder of a / b as the second argument.


[#77233] Tuesday, July 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;