guest@itl:~/home/algebra$
templates/binary-exponentiation.cpp
compilable
$cat templates/binary-exponentiation

Binary Exponentiation

Fast exponentiation using binary representation of the exponent in O(log n) multiplications.

#binary-exponentiation#power#modular#fast-power
$git shortlog -sn// 1 contributor
contributors --listcredits
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

ll binpow(ll a, ll b) {
  ll res = 1;
  while (b > 0) {
    if (b & 1) res *= a;
    a *= a;
    b >>= 1;
  }
  return res;
}

ll binpow(ll a, ll b, ll m) {
  if (m == 1) return 0;
  a %= m;
  ll res = 1;
  while (b > 0) {
    if (b & 1) res = (__int128)res * a % m;
    a = (__int128)a * a % m;
    b >>= 1;
  }
  return res;
}
25 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Binary Exponentiation

Compute ana^n in O(logn)O(\log n) multiplications by decomposing the exponent into its binary representation:

an=i:bi=1a2ia^n = \prod_{i:\, b_i = 1} a^{2^i}

How It Works

  • Start with result=1\text{result} = 1

  • While n>0n > 0: if the lowest bit of nn is 1, multiply result by current base

  • Square the base and right-shift nn each iteration

  • For the modular version, reduce mod mm after every multiplication
  • When to Use

  • Computing anmodma^n \bmod m for very large nn

  • Matrix exponentiation for Fibonacci / linear recurrences

  • Permutation exponentiation — applying a permutation kk times

  • Counting walks of length kk via adjacency matrix powers
  • Complexity

  • Time — O(logn)O(\log n) multiplications

  • Space — O(1)O(1)