Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to multiply the result by x when n is odd.
DSA C#
if (n % 2 == 1) result = result [1] x;
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using division or subtraction which changes the value incorrectly.
✗ Incorrect
When n is odd, multiply the current result by x to include the extra factor.
2fill in blank
mediumComplete the code to halve the exponent n in each iteration.
DSA C#
n = n [1] 2;
Attempts:
3 left
💡 Hint
Common Mistakes
Using floating division which results in a float.
Using subtraction which decreases n by 2 instead of halving.
✗ Incorrect
Use integer division to halve n, discarding any remainder.
3fill in blank
hardFix the error in squaring x for the next iteration.
DSA C#
x = x [1] x;Attempts:
3 left
💡 Hint
Common Mistakes
Using addition which doubles x but does not square it.
Using division or subtraction which changes the value incorrectly.
✗ Incorrect
To square x, multiply it by itself.
4fill in blank
hardFill the blank to complete the while loop condition.
DSA C#
int result = 1; while (n [1] 0) { if (n % 2 == 1) result = result * x; x = x * x; n = n / 2; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than in the loop condition.
Using incorrect comparison operators that cause infinite loops.
✗ Incorrect
The loop runs while n is greater than 0, and n is halved using integer division.
5fill in blank
hardFill all three blanks to complete the fast exponentiation method.
DSA C#
public static int FastPower(int x, int n) {
int result = [1];
while (n [2] 0) {
if (n % 2 == 1) result = result [3] x;
x = x * x;
n = n / 2;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing result to 0 which makes the final result always 0.
Using addition instead of multiplication for accumulating the result.
✗ Incorrect
Initialize result to 1, loop while n > 0, multiply result by x when n is odd.
