Challenge - 5 Problems
Factorial Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this factorial function call?
Consider this Rust function that calculates factorial using recursion. What will be printed when calling factorial(4)?
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(4));
}Attempts:
2 left
💡 Hint
Remember factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The factorial function multiplies n by factorial of n-1 until n is 0, where it returns 1. So factorial(4) = 4 * 3 * 2 * 1 = 24.
❓ Predict Output
intermediateWhat is the output of factorial(0)?
Using the same factorial function, what will be printed when calling factorial(0)?
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(0));
}Attempts:
2 left
💡 Hint
Factorial of zero is defined as 1.
✗ Incorrect
By definition, factorial(0) returns 1 as the base case in the recursion.
❓ Predict Output
advancedWhat error occurs when calling factorial with a negative number?
Suppose we change the factorial function parameter to i32 and call factorial(-1). What happens?
DSA Rust
fn factorial(n: i32) -> i32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(-1));
}Attempts:
2 left
💡 Hint
Think about what happens when recursion never reaches base case.
✗ Incorrect
Calling factorial(-1) causes infinite recursion because n never reaches 0, leading to stack overflow at runtime.
🧠 Conceptual
advancedWhy is recursion a good fit for factorial calculation?
Choose the best reason why recursion suits factorial calculation.
Attempts:
2 left
💡 Hint
Think about how factorial is mathematically defined.
✗ Incorrect
Factorial is naturally defined recursively, making recursion a direct and clear way to implement it.
❓ Predict Output
expertWhat is the output of this tail-recursive factorial function?
Analyze this Rust code using tail recursion. What will be printed when calling factorial_tail(5, 1)?
DSA Rust
fn factorial_tail(n: u32, acc: u32) -> u32 {
if n == 0 {
acc
} else {
factorial_tail(n - 1, acc * n)
}
}
fn main() {
println!("{}", factorial_tail(5, 1));
}Attempts:
2 left
💡 Hint
Tail recursion uses an accumulator to carry the result.
✗ Incorrect
The function multiplies acc by n each call, reducing n until zero, returning acc which holds factorial value.
