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
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 in multiplications by decomposing the exponent into its binary representation: