What is the main idea behind Fast Exponentiation (Power) algorithm?
It reduces the number of multiplications by repeatedly squaring the base and using the binary representation of the exponent, achieving O(log n) time complexity instead of O(n).
Click to reveal answer
beginner
Why does Fast Exponentiation run in O(log n) time?
Because it splits the exponent by half at each step using exponent / 2, so the number of steps grows logarithmically with the exponent size.
Click to reveal answer
intermediate
In Fast Exponentiation, what do you do when the exponent is odd?
Multiply the result by the base once, then reduce the exponent by 1 to make it even, and continue squaring.
Click to reveal answer
beginner
Show the Go code snippet for Fast Exponentiation function signature.
4. The following Go code for fast exponentiation has a bug. What is the bug?
func fastPower(base int, exp int) int {
if exp == 0 {
return 0
}
half := fastPower(base, exp/2)
if exp%2 == 0 {
return half * half
} else {
return half * half * base
}
}
medium
A. Function does not handle negative exponents
B. Missing multiplication by base for even exponents
C. Incorrect integer division for exp/2
D. Base case returns 0 instead of 1
Solution
Step 1: Check base case for exponent 0
Exponent 0 means power is 1, but code returns 0, which is incorrect.
Step 2: Verify other parts
Multiplication and division logic is correct; negative exponent handling is not required here.
Final Answer:
Base case returns 0 instead of 1 -> Option D
Quick Check:
Power of 0 exponent = 1 [OK]
Hint: Base case for exp=0 must return 1 [OK]
Common Mistakes:
Returning 0 for exp=0 base case
Ignoring negative exponent cases
Misplacing multiplication logic
5. You want to compute (3^13) mod 7 efficiently using fast exponentiation in Go. Which modification is needed in the fastPower function to correctly compute this without overflow?
hard
A. Add modulo operation after each multiplication to keep numbers small
B. Use float64 type for base and exponent to handle large numbers
C. Multiply only once at the end after all recursion completes
D. Increase the base to base*mod to avoid overflow
Solution
Step 1: Understand modular exponentiation
To avoid overflow and keep numbers small, apply modulo after each multiplication.
Step 2: Modify fastPower to include modulo
Insert modulo operation after multiplying halves and base to keep intermediate results within mod.
Final Answer:
Add modulo operation after each multiplication to keep numbers small -> Option A
Quick Check:
Modulo after multiplication prevents overflow [OK]
Hint: Apply modulo after every multiplication step [OK]
Common Mistakes:
Delaying modulo until end causes overflow
Using float64 instead of int causes precision loss
Multiplying base by mod increases value incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.