0PricingLogin
Competitive Programming Academy · Lesson

Fast Modular Exponentiation

Compute powers with pow(a, b, m).

The Power Problem

You often need a number raised to a giant exponent, all under a modulus. Multiplying one factor at a time would take far too many steps. ⚡

Naive Is Too Slow

A loop multiplying b times runs in O(b) steps. With an exponent near a billion, that blows past the time limit before it ever finishes.

for _ in range(b): r = r * a % MOD

All lessons in this course

  1. Work Modulo a Prime
  2. Fast Modular Exponentiation
  3. Modular Inverse via Fermat
  4. nCr with Precomputed Factorials
← Back to Competitive Programming Academy