To find the GCD of two numbers, you can use the Euclidean algorithm.
- If
b
is 0, returna
as the GCD. - Otherwise, call the function recursively with
b
anda % b
as the arguments. - Repeat until the second number becomes 0.
function gcd(a, b) {
if (b === 0) return a;
return gcd(b, a % b);
}
// Example usage
console.log(gcd(56, 98)); // Output: 14
console.log(gcd(100, 25)); // Output: 25
This method has a time complexity of O(log(min(a, b))), where a and b are the two numbers.
Tags: intermediate, JavaScript, Math, Algorithm