AdvancedMath for DSABit Manipulation & Math

Fast power: xⁿ in O(log n)

x¹³ = x⁸ · x⁴ · x¹: square x repeatedly and multiply in the squares where n's binary has a 1. With a mod, it also gives modular inverses.

The idea

Multiplying x by itself n times is . Instead write n in binary: 13 = 1101₂ = 8 + 4 + 1, so x¹³ = x⁸ · x⁴ · x¹. Squaring gives x, x², x⁴, x⁸… in log n steps; multiply in the ones you need.

With a modulus p, Fermat's little theorem gives division: a⁻¹ ≡ a^(p−2) mod p. That's how you compute nCr mod 10⁹ + 7.

Worked example

3¹³

  1. 13 = 1101 in binary. Squares: 3¹ = 3, 3² = 9, 3⁴ = 81, 3⁸ = 6,561.
  2. Bits set for 1, 4 and 8 → 3 × 81 × 6,561 = 1,594,323.
  3. 4 squarings instead of 12 multiplications.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

power(x, n):
result ← 1
while n > 0:
if the last bit of n is 1:
result ← result × x
x ← x × x(x, x², x⁴, x⁸, …)
n ← n >> 1
return result

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

3¹³

x = 3n = "13 (1101)"result = 1

Solution · Pythonline 2

def power(x, n, mod=None):
result = 1
while n > 0:
if n & 1: # this bit is set: use the current square
result = result * x if mod is None else result * x % mod
x = x * x if mod is None else x * x % mod
n >>= 1
return result
def inverse(a, p=10**9 + 7): # p must be prime
return power(a, p - 2, p)
# Python's built-in pow(x, n, mod) does the same.

Step 1 of 9· line 2

13 in binary is 1101: 13 = 8 + 4 + 1. So 3¹³ = 3⁸ × 3⁴ × 3¹. Keep squaring x (3, 3², 3⁴, 3⁸…) and multiply in the ones whose bit is set.

multiplications.

How to spot it

  • Pow(x, n), huge exponents, “mod 10⁹+7” with division, powers for fast .

Common mistakes

  • Negative exponents: compute power(1/x, −n).
  • Using a ** b % m in Python for huge b: pow(a, b, m) is far faster.

Practise the ideas first

Where it comes up

Go further