Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm.
DSA C#
int GCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a [1] b;
a = temp;
}
return a;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of remainder operator.
Using division '/' which returns quotient, not remainder.
✗ Incorrect
The Euclidean algorithm uses the remainder operator '%' to find the GCD by repeatedly replacing the larger number with the remainder of the division.
2fill in blank
mediumComplete the code to calculate the Least Common Multiple (LCM) of two numbers using their GCD.
DSA C#
int LCM(int a, int b) {
return (a [1] b) / GCD(a, b);
}Attempts:
3 left
💡 Hint
Common Mistakes
Adding numbers instead of multiplying.
Dividing numbers before multiplying.
✗ Incorrect
LCM is calculated by multiplying the two numbers and dividing by their GCD.
3fill in blank
hardFix the error in the GCD function to correctly swap values during the Euclidean algorithm.
DSA C#
int GCD(int a, int b) {
while (b != 0) {
int temp = a;
a = b;
b = [1];
}
return a;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'a % b' after 'a' has been updated.
Using 'temp % temp' which is always zero.
✗ Incorrect
The remainder should be calculated as temp % b, where temp holds the old value of a.
4fill in blank
hardFill both blanks to create a dictionary that maps numbers to their GCD with 12, only if the GCD is greater than 1.
DSA C#
var gcdMap = new Dictionary<int, int>();
int[] numbers = {2, 3, 4, 5, 6};
foreach (var num in numbers) {
int gcd = GCD(num, 12);
if (gcd [1] 1) {
gcdMap.Add(num, [2]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '>' in the condition.
Adding 'num' instead of 'gcd' as the dictionary value.
✗ Incorrect
We check if gcd is greater than 1, then add the number and its gcd to the dictionary.
5fill in blank
hardFill all three blanks to create a method that returns a dictionary mapping numbers to their LCM with 10, only if the LCM is less than 50.
DSA C#
Dictionary<int, int> GetLCMMap(int[] nums) {
var lcmMap = new Dictionary<int, int>();
foreach (var n in nums) {
int lcm = LCM(n, 10);
if (lcm [1] 50) {
lcmMap.Add([2], [3]);
}
}
return lcmMap;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' in the condition.
Swapping key and value in the dictionary add.
✗ Incorrect
We check if lcm is less than 50, then add the number and its lcm to the dictionary.
