Integer Power C++ Function with base and exponent parameters I would like to know if this is a good solution for a function that has to computer the power of integers given base and exponent.
The solution must include solution for negative numbers.
I'm trying to learn C++ trough a Deitel book and I'm doing several exercises.
#include &lt;iostream&gt;
using namespace std;

double integerPower(int base, int exponent){
    double result = 1;
    if(exponent &gt;=0){
    for (int i = 0; i &lt; exponent; i ++){
        result *= base;
        }
    } else {
        exponent *= -1;
        for (int i = 0; i &lt; exponent; i ++){
                result /= base;
                }
    }
    return result;
}

int main() {
    int base, exponent;
    double result;
    cout &lt;&lt; &quot;Insert the base: &quot; &lt;&lt; endl;
    cin &gt;&gt; base;
    cout &lt;&lt; &quot;Insert the exponent: &quot; &lt;&lt; endl;
    cin &gt;&gt; exponent;
    result = integerPower(base, exponent);
    cout &lt;&lt;&quot;The result is: &quot; &lt;&lt; result &lt;&lt; endl;
    return 0;
}
Use the standard library
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.
A pure integer power function
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 &amp; 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.