Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to multiply the result by x when n is odd.
DSA Java
if (n % 2 == 1) result = result [1] x;
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using division which reverses multiplication.
Using subtraction which does not accumulate powers.
✗ Incorrect
When n is odd, multiply the current result by x to include the extra factor.
2fill in blank
mediumComplete the code to square x in each iteration.
DSA Java
x = x [1] x;Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using division which reduces the value.
Using subtraction which changes the value incorrectly.
✗ Incorrect
Squaring x means multiplying x by itself to prepare for the next power step.
3fill in blank
hardFix the error in the loop condition to run while n is greater than zero.
DSA Java
while (n [1] 0) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than which never enters the loop if n starts positive.
Using equality which runs only if n is zero.
Using less or equal which may cause infinite loops.
✗ Incorrect
The loop should continue while n is greater than zero to process all bits.
4fill in blank
hardFill both blanks to update n by dividing it by 2 using right shift.
DSA Java
n = n [1] 1; // shift right by 1 // or equivalently n = n [2] 2;
Attempts:
3 left
💡 Hint
Common Mistakes
Using left shift which multiplies by 2.
Using multiplication which increases n.
Using left shift or multiplication in place of division.
✗ Incorrect
Right shift by 1 divides n by 2. Using / 2 also divides n by 2.
5fill in blank
hardFill all three blanks to complete the fast exponentiation method.
DSA Java
public static long fastPower(long x, long n) {
long result = 1;
while (n [1] 0) {
if ((n & 1) == 1) result = result [2] x;
x = x [3] x;
n = n >> 1;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using wrong loop condition operators.
Forgetting to square x each iteration.
✗ Incorrect
Loop while n > 0, multiply result by x when n is odd, and square x each iteration.
