Effectively calculate the result of geometric series Given \$f(n) = 1 + x + x^2 + x^3 + \ldots + x^n\$ and the fact that computers take more time when multiplying two numbers than when adding, how can we work out the result with greater efficiency?

#include &lt;iostream&gt;
using namespace std;

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

    double result = powerWithIntExponent(base, exponent &gt;&gt; 1);
    result *= result;
    if ((exponent &amp; 0x1) == 1) {
        result *= base;
    }
    return result;
}

double func(double x, int n)
{
    if (x == 0) return 1;
    if (x == 1) return n+1;

    double sum = 0;
    double x_n = 0;
    x_n = powerWithIntExponent(x, n+1);// the Geometric series start from x^0
    sum = (1-x_n)/(1-x);
    return sum;

}
int main(int argc, const char * argv[])
{

    double result = func(2, 2);
    cout&lt;&lt;result&lt;&lt;endl;
    return 0;
}
Instead of using a recursive algorithm (which might overflow the stack for large exponents) and calculating the power yourself, use the pow function which is likely pretty optimized.

#include &lt;iostream&gt;
#include &lt;cmath&gt;

using namespace std;

double func(double x, int n)
{
    double x_n;

    x_n = pow(x, n+1);
    return (1-x_n)/(1-x);    
}

int main(int argc, const char * argv[])
{

    double result = func(2, 2);
    cout&lt;&lt;result&lt;&lt;endl;
    return 0;
}


Now a few minor remarks about your original code: be sure to be more consistent with your coding style. For example:

if(exponent == 0)
    return 1;
if (exponent == 1)
    return base;


vs.

if (x == 0) return 1;
if (x == 1) return n+1;


Personally, I'd always either write it on one line as in the second example or if there is a newline, I'd always add braces. For reasons see Apple's goto fail;. But it's actually a personal preference, you don't need to do it that way but I highly recommend that you chose one style and stick to it.

(Same with whitespace: there should be a space after the if in if(exponent == 0))

Consistency would also be nice here:

if ((exponent &amp; 0x1) == 1)


Either use 0x1 both times or 1 both times. I feel that mixing these isn't a good idea.