Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications.

Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications.
mults = 0
def power(x, n):
    global mults
    if n == 0: return 1
    half = power(x, n // 2)
    mults += 1
    r = half * half
    if n % 2:
        mults += 1; r *= x
    return r
print(power(3, 13), mults)
What is printed?
  1. A. 1594323 12
  2. B. 1594323 6
  3. C. 1594323 7
  4. D. 531441 7

Correct answer: C. 1594323 7

13 = 1101₂: each level squares (one multiplication) and multiplies by x when the bit is 1. Levels for 13, 6, 3, 1 → 4 squarings + 3 extra (13, 3, 1 are odd) = 7, instead of 12 naive multiplications. 3¹³ = 1594323. O(log n).

More Coding Interview Problems questions

Exams that ask this topic