templates/modular-arithmetic-helpers.cpp
compilable
$cat templates/modular-arithmetic-helpers
Modular Arithmetic Helpers
Safe modular add, multiply, binary exponentiation, Russian peasant multiplication, and big mod.
#modular#binpow#int128#overflow-safe
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void addMod(ll &a, ll b, ll mod) {
a = (a + b % mod + mod) % mod;
}
void mulMod(ll &a, ll b, ll mod) {
a = ((__int128)a * b) % mod;
}
ll binpow(ll b, ll e, ll mod) {
ll res = 1; b %= mod;
while (e > 0) {
if (e & 1) res = ((__int128)res * b) % mod;
b = ((__int128)b * b) % mod;
e >>= 1;
}
return res;
}
ll binpow(ll b, ll e) {
ll res = 1;
while (e > 0) {
if (e & 1) res *= b;
b *= b;
e >>= 1;
}
return res;
}
ll binaryMul(ll a, ll b, ll mod) {
ll res = 0; a %= mod;
while (b > 0) {
if (b & 1) { res += a; if (res >= mod) res -= mod; }
a += a; if (a >= mod) a -= mod;
b >>= 1;
}
return res;
}
ll bigMod(const string &s, ll mod) {
ll res = 0;
for (char c : s)
res = (res * 10 + (c - '0')) % mod;
return res;
}48 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Modular Arithmetic Helpers
Functions
(__int128) to avoid overflow(__int128)__int128 isn't available__int128 vs binaryMul
__int128 — constant time multiply, preferred defaultbinaryMul — but portable to all judges