DSA Factory
Free Math and bits lessonsMath and bits · Stage 1 · Primes and remainders · Step 2

Square and halve

Compute a huge power's remainder quickly by squaring. About 10 minutes.

Remainders can be taken early

Think of a car odometer that rolls over: only the last digits matter. Taking a remainder works the same way. Multiply two numbers and then reduce, or reduce each first and then multiply, and the answer is identical.

So reduce after every single multiplication, and the numbers never get large.

Multiply, then reduce: every single time.
In code
(7 * 8) % 5                  # 1
((7 % 5) * (8 % 5)) % 5      # 1
2^10 % 1000, squaring and halving
baresult
start
10
2
1
round 1
round 2
round 3
round 4

Start: result = 1. Instead of multiplying by 2 ten times, we'll square.

Move 1 of 5

Halve the exponent

Computing 2 to the power 10 by multiplying ten times is slow. But it equals 4 to the power 5: square the base and halve the exponent. When the exponent is odd, first move one copy of the base into the result.

Each round halves the exponent, so even a million needs only about 20 rounds.

Use 64-bit numbers: squaring can reach 10 to the power 18 before you reduce.
In code
result = 1 % m
a %= m
while b > 0:
    if b % 2 == 1:
        result = result * a % m
    a = a * a % m
    b //= 2
return result
Quick check

How many squaring rounds does fast power need for b = 1,000,000?

  1. AAbout 20
  2. BAbout 1,000,000
  3. CAbout 1,000
Show the answer

About 20. 1,000,000 halves to 0 in about 20 steps, one round each.

Your problem

Power with remainder

Return a^b % m. (a^0 is 1, and anything % 1 is 0.)

Example
a = 2, b = 10, m = 1000 → 24

0 ≤ a ≤ 10^9 · 0 ≤ b ≤ 10^18 · 1 ≤ m ≤ 2 × 10^9

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve