Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the base case value for factorial of 0.
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
return [1];
}
n * factorial(n - 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 instead of 1 for the base case.
Returning n which causes infinite recursion.
✗ Incorrect
The factorial of 0 is defined as 1, so the base case returns 1.
2fill in blank
mediumComplete the recursive call to calculate factorial of n.
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
return 1;
}
n [1] factorial(n - 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' causing wrong results.
Using '-' or '/' which are incorrect for factorial.
✗ Incorrect
Factorial multiplies n by factorial of n-1, so the operator is *.
3fill in blank
hardFix the error in the base case condition to stop recursion correctly.
DSA Rust
fn factorial(n: u32) -> u32 {
if n [1] 0 {
return 1;
}
n * factorial(n - 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '<' which do not correctly identify the base case.
Using '!=' which causes infinite recursion.
✗ Incorrect
The base case should check if n equals 0 to stop recursion.
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from n down to 1.
DSA Rust
fn sum_to_n(n: u32) -> u32 {
if n == 0 {
return 0;
}
n [1] sum_to_n(n [2] 1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition.
Calling sum_to_n with n+1 causing infinite recursion.
✗ Incorrect
To sum numbers, add n to sum_to_n(n-1).
5fill in blank
hardFill all three blanks to write a recursive function that computes the nth Fibonacci number.
DSA Rust
fn fibonacci(n: u32) -> u32 {
if n == 0 || n == 1 {
return n;
}
fibonacci([1]) [2] fibonacci([3])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using wrong indices like n+1 or n-3.
✗ Incorrect
Fibonacci is sum of fibonacci(n-1) and fibonacci(n-2).
