guest@cp-base:~/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.

[Algebra]|
Jul 9, 2026
|explanatory_notes.md|
#binary-exponentiation#power#modular#fast-power
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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)