Objective
Computing b^e by multiplying e times is slow. Fast exponentiation takes advantage of the fact that b^e = (b^(e//2))^2 (× b if e is odd): with half the exponent the rest is solved, and the number of multiplications grows only with the logarithm of the exponent.
Instructions
- Read the base and the exponent (integers, exponent greater than or equal to 0), one per line.
- Define a recursive
power(base, exponent): ifexponentis 0 return 1; otherwise computepower(base, exponent // 2), multiply that result by itself and, ifexponentis odd, also multiply bybase. - Count the multiplications: one per level (the square) and one more when the exponent is odd.
- Show
base^exponent = resultand thenMultiplications: m.
2
10
2^10 = 1024
Multiplications: 6
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise