Complete the code to calculate the GCD of two numbers using the Euclidean algorithm.
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % [1];
a = temp;
}
return a;
}The Euclidean algorithm replaces b with the remainder of a divided by b, which is a % b. So the blank should be b.
Complete the code to calculate the LCM of two numbers using their GCD.
public static int lcm(int a, int b) {
return (a * b) / [1](a, b);
}The LCM is calculated by dividing the product of the two numbers by their GCD, so the blank should be the gcd function.
Fix the error in the recursive GCD function by completing the return statement.
public static int gcdRecursive(int a, int b) {
if (b == 0) {
return a;
}
return gcdRecursive([1], a % b);
}The recursive call swaps the parameters: the first becomes b and the second becomes a % b.
Fill both blanks to create a method that returns both GCD and LCM as an array.
public static int[] gcdAndLcm(int a, int b) {
int gcd = [1](a, b);
int lcm = (a * b) / [2];
return new int[]{gcd, lcm};
}The first blank calls the gcd function. The second blank uses the gcd variable to calculate LCM.
Fill all three blanks to create a method that returns a map with keys "GCD" and "LCM" for two numbers.
public static Map<String, Integer> gcdLcmMap(int a, int b) {
Map<String, Integer> result = new HashMap<>();
int gcdValue = [1](a, b);
int lcmValue = (a * b) / [2];
result.put("GCD", [3]);
result.put("LCM", lcmValue);
return result;
}The method calls gcdValue = gcd(a, b). The LCM divides by gcdValue. The map stores gcdValue for "GCD" key.
