Integer Power C++ Function with base and exponent parameters


If you are going to give the result as a double, then this function isn’t really a pure integer power calculator. And in that case, just use std::pow(). It has overloads for integer exponents that the compiler can optimize for.

If the base and the exponent are both negative, then mathematically the result will be a complex number. Either you want to return a std::complex<double>, or you should somehow deal with this situation and return a NaN, or signal an error in some other way.

If you just want to work purely on integers, then the typical algorithm to calculate a number raised to an arbitrary power efficiently is by recognizing that, for example, $x^4 = ((x * x) * (x * x))$, and so you can calculate $y = x * x$, and then $x^4 = y * y$. This only needs two multiplications instead of 3. So basically, you can divide and conquer the problem:

int integerPower(int base, int exponent) {
    if (exponent == 0)
        return 1;

    int result = integerPower(base, exponent / 2);
    int result *= result;

    if (exponent & 1)
            result *= base;

    return result;
}    

The above doesn’t work for negative exponents, but then again that is not very useful if the result is just an integer.