Power
2⁵ = 2 * 2 * 2 * 2 * 2
m^n = m * m * m ... for n times
pow(m, n) = (m * m * m ... * n - 1 times) * m
pow(m, n) = pow(m, n - 1) * m
pow(m, n) = 1 if n = 0
pow(m, n - 1) * m if n > 0
int pow(int m, int n) {
if (n == 0)
return 1;
return pow(m, n - 1) * m;
}
We can also reduce the number of operations like this:
2⁸ = (2 * 2)⁴
2⁹ = 2 * (2 * 2)⁴
With that, we can rewrite the power function:
int pow(int m, int n) {
if (n == 0)
return 1;
if (n % 2 == 0)
return pow(m * m, n / 2);
else
return m * pow(m * m, (n - 1) / 2);
}