summaryrefslogtreecommitdiff
path: root/math/modExp.cpp
blob: cd0f982c28c6a5c2b44e39dded58ce150c6daeb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Laufzeit: O(log(b))
ll mult_mod(ll a, ll b, ll n) {
	if(a == 0 || b == 0) return 0;
	if(b == 1) return a % n;
	
	if(b % 2 == 1) return (a + mult_mod(a, b-1, n)) % n;
	else return mult_mod((a + a) % n, b / 2, n);
}

// Laufzeit: O(log(b))
ll pow_mod(ll a, ll b, ll n) {
	if(b == 0) return 1;
	if(b == 1) return a % n;
	
	if(b % 2 == 1) return mult_mod(pow_mod(a, b-1, n), a, n);
	else return pow_mod(mult_mod(a, a, n), b / 2, n);
}