Complete the code to return the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % [1];
a = temp;
}
return a;
}The Euclidean algorithm replaces a by b and b by a % b until b becomes zero. So, a % b is the correct expression.
Complete the code to calculate the least common multiple (LCM) of two numbers using their GCD.
function lcm(a, b) {
return (a * b) / [1](a, b);
}The formula for LCM is (a * b) / gcd(a, b). So, we use the gcd function here.
Fix the error in the recursive GCD function by completing the base case condition.
function gcdRecursive(a, b) {
if (b [1] 0) {
return a;
}
return gcdRecursive(b, a % b);
}The base case for the recursive GCD is when b == 0. Then, a is the GCD.
Fill both blanks to create a function that returns an object with GCD and LCM of two numbers.
function gcdAndLcm(a, b) {
const gcdValue = [1](a, b);
const lcmValue = (a * b) / [2];
return { gcd: gcdValue, lcm: lcmValue };
}First, we call the gcd function to get the GCD. Then, we divide the product by gcdValue to get the LCM.
Fill all three blanks to create a function that returns an array with GCD and LCM of two numbers using recursion.
function gcdLcmArray(a, b) {
const gcdValue = [1](a, b);
const lcmValue = (a * b) / [2];
return [gcdValue, [3]];
}We use the recursive gcd function gcdRecursive to get gcdValue. Then calculate lcmValue. Finally, return an array with gcdValue and lcmValue.
