Recursion · 16 / 18 Exercise Hard

Fast exponentiation

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): if exponent is 0 return 1; otherwise compute power(base, exponent // 2), multiply that result by itself and, if exponent is odd, also multiply by base.
  • Count the multiplications: one per level (the square) and one more when the exponent is odd.
  • Show base^exponent = result and then Multiplications: m.
Input
2
10
Output
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