Challenge - 5 Problems
Fast Exponentiation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of fast exponentiation function
What is the output of this Rust function when computing 2 to the power 10?
DSA Rust
fn fast_pow(base: i32, exp: i32) -> i32 {
if exp == 0 {
return 1;
}
let half = fast_pow(base, exp / 2);
if exp % 2 == 0 {
half * half
} else {
half * half * base
}
}
fn main() {
println!("{}", fast_pow(2, 10));
}Attempts:
2 left
💡 Hint
Remember that 2^10 means multiplying 2 by itself 10 times.
✗ Incorrect
The function uses fast exponentiation by dividing the exponent by 2 recursively. 2^10 equals 1024.
❓ Predict Output
intermediateOutput of fast exponentiation with odd exponent
What will be printed when running this Rust code for base=3 and exponent=5?
DSA Rust
fn fast_pow(base: i32, exp: i32) -> i32 {
if exp == 0 {
return 1;
}
let half = fast_pow(base, exp / 2);
if exp % 2 == 0 {
half * half
} else {
half * half * base
}
}
fn main() {
println!("{}", fast_pow(3, 5));
}Attempts:
2 left
💡 Hint
3^5 means 3 multiplied by itself 5 times.
✗ Incorrect
3^5 = 3*3*3*3*3 = 243. The function correctly calculates this using recursion.
🔧 Debug
advancedIdentify the error in this fast exponentiation code
What error will this Rust code produce when compiled and run?
DSA Rust
fn fast_pow(base: i32, exp: i32) -> i32 {
if exp == 0 {
return 1;
}
let half = fast_pow(base, exp >> 1);
if exp % 2 == 0 {
half * half
} else {
half * half * base
}
}
fn main() {
println!("{}", fast_pow(2, -3));
}Attempts:
2 left
💡 Hint
Consider what happens when the exponent is negative.
✗ Incorrect
The function does not handle negative exponents, so the recursive calls never reach the base case, causing infinite recursion and stack overflow.
❓ Predict Output
advancedOutput of fast exponentiation with zero exponent
What is the output of this Rust code when computing 5 to the power 0?
DSA Rust
fn fast_pow(base: i32, exp: i32) -> i32 {
if exp == 0 {
return 1;
}
let half = fast_pow(base, exp / 2);
if exp % 2 == 0 {
half * half
} else {
half * half * base
}
}
fn main() {
println!("{}", fast_pow(5, 0));
}Attempts:
2 left
💡 Hint
Any number to the power 0 is 1.
✗ Incorrect
The base case returns 1 when exponent is 0, so the output is 1.
🧠 Conceptual
expertTime complexity of fast exponentiation algorithm
What is the time complexity of the fast exponentiation algorithm implemented recursively as shown in previous examples?
Attempts:
2 left
💡 Hint
The exponent is divided by 2 at each recursive call.
✗ Incorrect
The algorithm reduces the exponent by half each time, so it runs in logarithmic time relative to the exponent.
