Fast exponentiation and modular arithmetic

Video lessonComing soon

1 Two problems with big powers

Some problems ask for a number like 5 to the power 10¹⁵, "modulo 10⁹ + 7". The plain way multiplies 5 by itself again and again. That runs into two problems.

  • Too many steps. Raising x to the power n this way takes n − 1 multiplications. At n = 10¹⁵ that is around 10¹⁵ steps. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).
  • Too large a number. Even 2¹⁰⁰ has 31 digits. A 64-bit integer holds up to about 9.2 × 10¹⁸, so the value overflows long before the end.

Fast exponentiation fixes the first problem. It needs only about log n multiplications. Modular arithmetic fixes the second. It keeps every number below 10⁹ + 7 the whole way. Together they calculate 5 to the power 10¹⁵, modulo 10⁹ + 7, in about 100 multiplications.

2 Halving the exponent

The recursion tree lesson showed the start of this trick for an even exponent: x¹⁶ = (x⁸)², so one call on half the exponent and one multiplication give the answer. An odd exponent needs one more step. We take one x out first, and the rest is even: x¹¹ = x × x¹⁰ = x × (x⁵)².

So there are three cases. Here n / 2 is rounded down, so for n = 11 it is 5, and 5 + 5 + 1 = 11.

  • n is 0. The answer is 1.
  • n is even. xn = (xn/2)².
  • n is odd. xn = x × (xn/2)².
power(x, n)
    if n == 0
        return 1
    half = power(x, n / 2)
    if n is even
        return half * half
    return x * half * half

For 3¹¹, each call makes one call on half its exponent, so the calls form a single line:

3⁰3¹3²3⁵3¹¹
The calls for 3¹¹. The exponent goes 11, 5, 2, 1, 0

The answers come back from the bottom up:

nhalfReturns
0—1
1, odd13 × 1 × 1 = 3
2, even33 × 3 = 9
5, odd93 × 9 × 9 = 243
11, odd2433 × 243 × 243 = 177147

Each call does one or two multiplications, and the exponent halves on the way down. So there are only about log n calls.

3 Reading the exponent in binary

A loop does the same work without the call stack, and it is the version most solutions use. It rests on binary. 11 in binary is 1011, so 11 = 8 + 2 + 1, and

3¹¹ = 3⁸ × 3² × 3¹

The powers 3¹, 3², 3⁴ and 3⁸ come from squaring, because each one is the one before it squared. So the loop keeps a variable base, squares it every turn, and multiplies it into result on the turns where the exponent's bit is 1. Each turn reads the lowest bit and then drops it:

  1. If n is odd, its lowest bit is 1, so multiply result by base.
  2. Square base.
  3. Halve n, which drops the lowest bit.

Before the loop, result is 1 and base is 3¹. The bits are read from the right:

3¹¹ with the binary loop
18041211bit
11 in binary
5n3²base3¹result
Turn 1: the bit is 1, so result = 1 × 3¹. Then base becomes 3² and n becomes 5

The boxes show each variable after its turn. The exponent of result adds up the bits that are 1: 1, then 1 + 2, then 1 + 2 + 8 = 11. With real numbers, the same four turns are:

Turnnn % 2resultbase after squaring
11111 × 3 = 39
2513 × 9 = 2781
320276561
41127 × 6561 = 17714743046721

The loop ends with 177147, the same as the recursion. The last column shows the second problem. After four turns, base already has 8 digits, and two more squarings take it past 64 bits.

4 Keeping numbers small with a modulus

Problems with huge answers ask for the answer modulo 10⁹ + 7: the remainder after dividing by 1,000,000,007. This number is chosen for a few reasons:

  • A remainder fits in a 32-bit int. It is always below 10⁹ + 7.
  • The product of two remainders fits in 64 bits. It is below about 10¹⁸, and 64 bits hold up to about 9.2 × 10¹⁸.
  • It is prime. That matters for division, in the next lesson.

Two rules let us take the remainder after every step instead of once at the end:

(a + b) mod m = ((a mod m) + (b mod m)) mod m
(a × b) mod m = ((a mod m) × (b mod m)) mod m

Here is a check with small numbers and m = 7. 23 × 19 = 437, and 437 mod 7 = 3. With the remainders first, 23 mod 7 = 2 and 19 mod 7 = 5. Then 2 × 5 = 10, and 10 mod 7 = 3, the same answer.

The reason is short. 23 = 3 × 7 + 2 and 19 = 2 × 7 + 5. When we multiply these out, every part except 2 × 5 has a 7 in it. Those parts leave no remainder, so only 2 × 5 decides the answer.

So in the loop, we take % MOD right after each multiplication. Then result and base always stay below 10⁹ + 7, and every product fits in 64 bits.

5 Subtraction and division

Addition and multiplication follow the rules above. The other two operations need care.

Subtraction can go negative. Take a = 10⁹ + 10 and b = 5. a − b is positive, but a mod m is 3, and 3 − 5 = −2. Adding m before the last mod fixes it:

(a − b) mod m = ((a mod m) − (b mod m) + m) mod m

Here that gives (3 − 5 + m) mod m = 1,000,000,005, the right answer.

C++

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %.

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %. Math.floorMod also returns the remainder that is never negative.

% is never negative here. -2 % MOD is already 1000000005, so the extra + MOD is not needed. It does no harm.

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %.

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %.

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %. rem_euclid(MOD) also returns the remainder that is never negative.

% keeps the minus sign. -2 % MOD is −2, so we add MOD before the last %.

Division does not work this way. (12 / 4) mod 5 is 3. With the remainders first, we get 2 / 4, which is not even a whole number. Division under a modulus needs a different tool, the modular inverse. The next lesson, on nCr, uses it, and fast power is what calculates it cheaply.

6 The code, and what it costs

The code is the binary loop with % MOD after each multiplication. It also takes base % MOD at the start, in case the base itself is larger than MOD.

C++

64-bit products. result and base are long long, so base * base is calculated in 64 bits. With int, it overflows before % MOD runs.

64-bit products. result and base are long, so base * base is calculated in 64 bits. With int, it overflows before % MOD runs.

Built in. pow(3, 11, MOD) does the same loop. Integers never overflow, but the mod still keeps the numbers small and the loop fast.

BigInt. A product reaches about 10¹⁸, and a Number is exact only up to about 9 × 10¹⁵. So the code works in BigInt (3n, 11n), and Number(modPow(3n, 11n)) turns the answer back into a Number.

64-bit products. result and base are int64, so base * base is calculated in 64 bits.

64-bit products. result and base are i64, so base * base is calculated in 64 bits. With i32, it overflows before % MOD runs.

baseValue. base is a keyword in C#, so the variable has another name. It is a long, so baseValue * baseValue is calculated in 64 bits.

modPow(3, 11) returns 177147, and modPow(2, 100) returns 976371285.

Each turn halves exponent, so the loop runs about log n times. An exponent of 10¹⁵ halves about 50 times before it reaches 0. Each turn does at most two multiplications, so that is about 100 multiplications. The space is O(1): result, base and exponent. The recursive version also takes O(log n) time, but its call stack takes O(log n) space.

Multiply n times10¹⁵Fast power100about 1 second
Multiplications for an exponent of 10¹⁵, on a scale where each mark is ten times the last

7 Mistakes and edge cases

  • Taking the mod only at the end. Without % MOD inside the loop, the numbers overflow. In Java, modPow(2, 100) then returns 0 instead of 976371285, because 2⁶⁴ wraps around to exactly 0 in 64 bits.
  • A 32-bit result or base. Both stay below 10⁹ + 7, but their product does not fit in 32 bits. modPow(1000000000, 2) should return 49. With int in Java, it returns −486618617, a Wrong Answer.
  • A negative exponent. In a problem like Pow(x, n), with a decimal x, x−n = 1 / xn. So we raise x to the power |n| and divide 1 by the result.
  • The smallest int as the exponent. With n = −2147483648, flipping the sign in a 32-bit int gives −2147483648 again, because 2147483648 does not fit. We copy n into a 64-bit variable first, then flip its sign.

8 When to use it

A problem needs these ideas when its answer grows too fast to store:

  • "Return the answer modulo 10⁹ + 7." We take the mod after every addition and multiplication, and add the mod back after a subtraction.
  • A huge exponent. A power with an exponent up to 10⁹ or 10¹⁸ needs fast power.
  • The same choice repeated many times. When each of n places has 5 options, there are 5n ways, and that is a fast power.
  • Division under a modulus. That needs the modular inverse, from the next lesson.

The habit to keep: every multiplication under a modulus is followed by % MOD on the same line, and both sides of it are 64-bit.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.