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?- A. 1594323 12
- B. 1594323 6
- C. 1594323 7
- 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
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…
- Problem: Count set bits for each number 0..n using DP on the lowest bit. python def bits(n): r = [0] (n + 1) for i in range(1, n + 1)…
- Problem: Check whether a number is a power of two and isolate its lowest set bit. python print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x…
- Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space. python def single(a): ones = twos…
- Problem: Two values appear once and every other value twice. Find both (smaller first). python def twosingle(a): x = 0 for v in a: x ^= v…
- Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array. python def ham(x, y)…