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 Rust
fn gcd(mut a: i32, mut b: i32) -> i32 {
while b != 0 {
let temp = b;
b = a [1] b;
a = temp;
}
a
}Attempts:
3 left
💡 Hint
Common Mistakes
Using division (/) instead of modulus (%) causes incorrect results.
Using subtraction (-) instead of modulus (%) is less efficient.
✗ Incorrect
The Euclidean algorithm uses the remainder operation (%) to update b with the remainder of a divided by b.
2fill in blank
mediumComplete the code to calculate the least common multiple (LCM) of two numbers using the GCD function.
DSA Rust
fn lcm(a: i32, b: i32) -> i32 {
(a * b) [1] gcd(a, b)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition (+) instead of division (/) leads to wrong results.
Using modulus (%) or subtraction (-) is incorrect here.
✗ Incorrect
LCM is calculated by dividing the product of the two numbers by their GCD.
3fill in blank
hardFix the error in the gcd function to correctly swap values during the Euclidean algorithm.
DSA Rust
fn gcd(mut a: i32, mut b: i32) -> i32 {
while b != 0 {
let temp = a;
a = b;
b = [1];
}
a
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a % b after a is updated causes wrong remainder.
Using temp % a is incorrect because a has changed.
✗ Incorrect
After swapping, b should be updated to the remainder of the old a (temp) divided by b.
4fill in blank
hardFill both blanks to create a function that returns a tuple with GCD and LCM of two numbers.
DSA Rust
fn gcd_lcm(a: i32, b: i32) -> (i32, i32) {
let gcd_value = gcd(a, b);
let lcm_value = (a * b) [1] gcd_value;
([2], lcm_value)
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'a' instead of gcd_value in the tuple.
Using multiplication (*) instead of division (/) for LCM.
✗ Incorrect
LCM is product divided by GCD, and the tuple returns (GCD, LCM).
5fill in blank
hardFill all three blanks to implement a recursive GCD function and use it to compute LCM.
DSA Rust
fn gcd_recursive(a: i32, b: i32) -> i32 {
if b == 0 {
[1]
} else {
gcd_recursive(b, a [2] b)
}
}
fn lcm_using_recursive(a: i32, b: i32) -> i32 {
(a * b) [3] gcd_recursive(a, b)
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning b instead of a in base case.
Using subtraction (-) instead of modulus (%) in recursion.
Using multiplication (*) instead of division (/) for LCM.
✗ Incorrect
Base case returns a; recursive call uses modulus (%); LCM divides product by GCD.
