Arrays · Core Array Techniques

Binary Exponentiation

Computing x^n in O(log n) multiplications by squaring the base and only multiplying it into the result on the bits of n that are set.

  • 5 min read
  • 7 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. A second flavor: modular exponentiation
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

Binary exponentiation computes x^n with about 2 log2(n) multiplications instead of n - 1. It squares the base over and over, and multiplies it into the result wherever n's binary form has a 1 bit. With a modulus applied at every step, it computes huge powers like a^b mod m, the operation at the heart of RSA and Diffie-Hellman. The same loop raises matrices to powers, which jumps a linear recurrence like Fibonacci n steps ahead.

We'll go from simple to more technical:

  1. The pattern: square the base, halve the exponent, multiply in on 1 bits.
  2. A second flavor: modular exponentiation.
  3. Where repeated squaring runs in production (cryptography).
  4. The edge cases around it: negative exponents, Integer.MIN_VALUE, overflow.

The approach

Multiplying x by itself n times is O(n), far too slow when n is in the billions. Instead, write n in binary. 13 is 1101, which means 8 + 4 + 1. So 3^13 = 3^8 × 3^4 × 3^1. Squaring gives those pieces cheaply: 3, 9, 81, 6561 are 3^1, 3^2, 3^4, 3^8. Read the bits of n from the lowest one up. On a 1 bit, multiply the current piece into the result. Then square the piece and drop the bit.

Computing 3^13:

Exponent left (binary)Lowest bitCurrent pieceResult after this step
11011: multiply in33
1100: skip93
111: multiply in81243
11: multiply in6,5611,594,323

Four rounds instead of twelve multiplications.

Java

double result = 1.0;
double current = x;
long exponent = n;   // use a wider type - negating Integer.MIN_VALUE overflows an int
while (exponent > 0) {
    if ((exponent & 1) == 1) result *= current;   // this bit of n is set
    current *= current;                            // current becomes x^(2^k) each iteration
    exponent >>= 1;
}

Python

result = 1.0
current = x
exponent = n              # n >= 0 here: see "Negative exponents" below
while exponent > 0:
    if exponent & 1:      # this bit of n is set
        result *= current
    current *= current    # current becomes x^(2^k) each iteration
    exponent >>= 1

For a negative n, compute x to the power |n| with the same loop, then take 1 divided by the result.

A second flavor: modular exponentiation

The same loop with integers and a modulus computes (base^exp) mod m. That's the core step behind RSA and Diffie-Hellman:

Java

long result = 1 % m;
long b = base % m;
while (exp > 0) {
    if ((exp & 1) == 1) result = (result * b) % m;
    b = (b * b) % m;
    exp >>= 1;
}

Python

result = 1 % m
b = base % m
while exp > 0:
    if exp & 1:
        result = result * b % m
    b = b * b % m
    exp >>= 1
# Python's built-in pow(base, exp, m) does exactly this

The one new rule: reduce % m after every multiplication, not just at the end. A base squared a few times grows past what a 64-bit long can hold. Reducing at each step keeps every value below m. Then each product stays below m^2, which fits in a long for m up to about 3 × 10^9. Every modulus in this skill's questions is at most 10^9. For bigger moduli even one product overflows, so use BigInteger.modPow or a 128-bit multiply built on Math.multiplyHigh.

Where you'll see it

Cryptography depends on it. RSA and Diffie-Hellman compute a^b mod m with exponents hundreds of digits long. That's only possible in O(log b) multiplications, not O(b).

Which tool for which job?

You needUse
x^n for a large integer nbinary exponentiation, O(log n)
a^b mod mthe same loop, reducing mod m after every multiplication
A modular inverse (m prime)a^(m-2) mod m, or Python's pow(a, -1, m)
The n-th term of a linear recurrencea matrix raised to the n-th power
A modulus near 10^18 in JavaBigInteger.modPow, or a 128-bit-safe multiply
A small fixed power (x^2, x^3)just multiply

Common mistakes

MistakeWhat happensDo this instead
Ignoring negative exponentsa wrong answercompute 1 / x^n for -n
Negating Integer.MIN_VALUEit stays negativewiden to long first
Reducing mod m only at the endoverflow in Java; huge, slow numbers in Pythonreduce after every multiplication
(a * b) % m with m near 10^18 in Javathe product overflows longBigInteger or Math.multiplyHigh
Forgetting result = 1 % m when m is 1returns 1 instead of 0start from 1 % m

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. The loop only runs while exponent > 0. What happens for a negative n if nothing else is done?

Show answer

The loop never runs, so the function returns 1.0, which is wrong for any negative n. Handle it separately: compute x to the power |n|, then take the reciprocal.

2. Why reduce % m after every multiplication, not once at the end?

Show answer

Repeated squaring grows very fast. A few squarings can pass what a 64-bit long holds, and the value silently wraps. Reducing after each multiplication keeps every value below m, so each product stays below m^2.

3. Why does the same loop work for (base^exp) mod m and for plain x^n?

Show answer

Both rest on the same fact: the exponent is a sum of powers of two, so the answer is a product of squarings. Only the multiplication changes, from doubles to integers mod m. The loop stays the same.

Key takeaways

  • x^n is the product of x^(2^k) for every 1 bit k of n. Repeated squaring makes those O(log n) pieces.
  • Handle a negative exponent separately: compute the positive power, then the reciprocal.
  • Negating Integer.MIN_VALUE overflows. Widen to long first.
  • For a^b mod m, reduce after every multiplication.
  • Matrix exponentiation uses the same loop with matrix multiplication.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
x^n, large nsquare and multiply
a^b mod mreduce after every multiplication
Division mod a primea^(p-2) mod p / pow(a, -1, p)
The n-th term of a recurrencematrix power
m near 10^18 in JavaBigInteger.modPow

Snippets worth knowing by heart

Java

static long modPow(long base, long exp, long m) {
    long result = 1 % m;
    base %= m;
    while (exp > 0) {
        if ((exp & 1) == 1) result = result * base % m;   // safe while m < ~3e9
        base = base * base % m;
        exp >>= 1;
    }
    return result;
}

Python

def mod_pow(base: int, exp: int, m: int) -> int:
    result, base = 1 % m, base % m
    while exp > 0:
        if exp & 1:
            result = result * base % m
        base = base * base % m
        exp >>= 1
    return result          # same as pow(base, exp, m)

The traps

  • Negative exponents: the loop never runs and returns a wrong answer. Compute 1 / x^n for -n.
  • -Integer.MIN_VALUE is still negative in an int. Widen the exponent to long before negating.
  • Reducing only at the end: Java overflows and Python builds huge, slow numbers. Reduce after every multiplication.
  • (a * b) % m for large m: with m near 10^18 the product overflows long. Use Math.multiplyHigh or BigInteger.
  • m = 1: starting from 1 returns 1 instead of 0. Start from 1 % m.

Staff-level points, one line each

  • Invariant: result * base^exp = x^n.
  • n = 10^9: 42 multiplications; 3^1,000,000 has 477,122 digits.
  • Inverse of 3 mod 10^9 + 7: 333,333,336.
  • Matrix power: F(90) exactly; F(10^18) mod 10^9 + 7 = 209,783,453.
  • Java (a * a) % m with m = 10^18 + 3 gave a negative number; the answer was 196.

Say it in an interview

  • "I square the base and halve the exponent, multiplying in on each 1 bit."
  • "It's O(log n) multiplications."
  • "I reduce mod m after every step so numbers stay small."
  • "For a recurrence, the same loop raises a matrix to the n-th power."

Practice

This skill comes with 7 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Binary Exponentiation free

Pow(x, n)

MediumProCoding problemJava · Python

Raise a decimal number x to an integer power n, and print the result rounded to exactly 5 decimal places.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Modular Exponentiation

MediumProCoding problemJava · Python

Compute (base^exp) mod m. base, exp, and m can all be large (up to 10^9), so intermediate values must be reduced modulo m at every step to avoid overflow - use the same repeated-squaring loop as pow(x, n), but with modular arithmetic instead of doubles, in O(log exp)…

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Binary Exponentiation free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime