Predict the output
What does this print?
result, base, exp = 1, 3, 13
mults = 0
while exp:
if exp & 1:
result *= base
mults += 1
base *= base
exp >>= 1
print(result == 3 ** 13, mults)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True 3
Right: 13 is 1101 in binary, so three bits are set.
The result is multiplied once per set bit, and the loop runs once per bit, so the work is logarithmic in the exponent.
Why not the others?
- B True 13. Squaring skips most multiplications; only set bits multiply the result.
- C False 3. The bits of 13 pick 3¹ × 3⁴ × 3⁸, which is 3¹³.
Traced by running the Python solution.
Text version
2^10 mod 1000 (args [2, 10, 1000]):
Key: acc = the result so far; sq = the current square of the base; exp = the exponent still to use.
| Line | acc | sq | exp |
|---|---|---|---|
| 2 | 10 (changed) | ||
| 3 | 1 (changed) | 2 (changed) | 10 |
| 4 | 1 | 2 | 10 |
| 6 | 1 | 2 | 10 |
| 7 | 1 | 4 (changed) | 10 |
| 3 | 1 | 4 | 5 (changed) |
| 4 | 1 | 4 | 5 |
| 5 | 1 | 4 | 5 |
| 6 | 4 (changed) | 4 | 5 |
| 7 | 4 | 16 (changed) | 5 |
| 3 | 4 | 16 | 2 (changed) |
| 4 | 4 | 16 | 2 |
| 6 | 4 | 16 | 2 |
| 7 | 4 | 256 (changed) | 2 |
| 3 | 4 | 256 | 1 (changed) |
| 4 | 4 | 256 | 1 |
| 5 | 4 | 256 | 1 |
| 6 | 24 (changed) | 256 | 1 |
| 7 | 24 | 536 (changed) | 1 |
| 3 | 24 | 536 | 0 (changed) |
| 8 | 24 | 536 | 0 |
21 rows, result 24.
3^13 mod 1000 (args [3, 13, 1000]):
Key: acc = the result so far; sq = the current square of the base; exp = the exponent still to use.
| Line | acc | sq | exp |
|---|---|---|---|
| 2 | 13 (changed) | ||
| 3 | 1 (changed) | 3 (changed) | 13 |
| 4 | 1 | 3 | 13 |
| 5 | 1 | 3 | 13 |
| 6 | 3 (changed) | 3 | 13 |
| 7 | 3 | 9 (changed) | 13 |
| 3 | 3 | 9 | 6 (changed) |
| 4 | 3 | 9 | 6 |
| 6 | 3 | 9 | 6 |
| 7 | 3 | 81 (changed) | 6 |
| 3 | 3 | 81 | 3 (changed) |
| 4 | 3 | 81 | 3 |
| 5 | 3 | 81 | 3 |
| 6 | 243 (changed) | 81 | 3 |
| 7 | 243 | 561 (changed) | 3 |
| 3 | 243 | 561 | 1 (changed) |
| 4 | 243 | 561 | 1 |
| 5 | 243 | 561 | 1 |
| 6 | 323 (changed) | 561 | 1 |
| 7 | 323 | 721 (changed) | 1 |
| 3 | 323 | 721 | 0 (changed) |
| 8 | 323 | 721 | 0 |
22 rows, result 323.