Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Math & Number Theory/Math / Number Theory

Technique

Binary Exponentiation (fast power)

Compute a^n (mod m) in O(log n) by squaring and multiplying on set bits; generalises to matrices and any associative operation.

Learn firstMath / Number TheoryBit Tricks & BitmaskingUnlocksMatrix ExponentiationCombinatorics mod p (nCr, Catalan, stars and bars)Gaussian Elimination (mod p / reals) & Matrix-Tree TheoremFFT / NTT Convolution (and Walsh-Hadamard)+2
0%
mastery
0/9 solved
Practise nextPow(x, n)
IdeaPracticePitfalls

Recognise it

The signal

a^b mod p with b up to 1e18

  1. 1Brute force

    Multiply n times.

  2. 2The observation

    n multiplications: a^n = (a^(n/2))^2 * a^(n mod 2).

  3. 3Why it works

    result * base^remaining equals the target throughout.

Reach for it when

  • +modular inverse via Fermat a^(p-2)
  • +repeated application of an associative operation

Not when

  • ×modulus not prime when using Fermat inverses

Practice

Next

Pow(x, n)

0/9 solved
  • Bit StringsCSESEasy
  • Pow(x, n)Meta, GoogleMedium
  • ExponentiationCSESMedium
  • Exponentiation IICSESMedium
  • Fibonacci NumbersCSESMedium
  • Throwing DiceCSESMedium
  • Graph Paths ICSESMedium
  • Magic GemsCodeforces2100
  • Product Oriented RecurrenceCodeforces2300

Pitfalls

Misconceptions

  • !overflow in base*base before mod (use 128-bit or mulmod)
Go deeperresources

Resources

  • Binary exponentiationcp-algorithms · article
  • Sieve of Eratosthenescp-algorithms · article
  • Modular inversecp-algorithms · article
  • DivisibilityUSACO Guide · course
  • CombinatoricsUSACO Guide · course
  • Math cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems