leslie
leslie

Reputation: 17

Recursive power function in C++

I'm having some trouble with this function. The function takes a and computes it to the power of b recursively. My compiler gives me a segmentation error when I compile this, which I'm not sure how to fix. Can anyone help?

/****   Recursive power function   > Computes a^b, where b can be positive or negative*****/
        int recPower(double a, int b)
        {   
            if (b == 0)
            {
                return 1;
            }
            else
            {
                return (a *recPower(a, b-1));
            }
          }

/* Computes a^b (power function) */    
cout << "POWER" << endl;    
cout << "----------" << endl;    
int a = 2, b = -3;    
cout << a << "^" << b << " = ";    
cout << recPower(a, b) << endl;    
cout << endl;    

Upvotes: 0

Views: 1097

Answers (2)

selbie
selbie

Reputation: 104514

The crash is a result of infinite recursion. b never reaches 0 since you keep decrementing it on every recursive step.

You probably need to insert this clause into your code:

if (b < 0)
{
    return 1.0 / recPower(a,-b);
} 
else if (b == 0)
...

Of course, a to the power of a negative number will more sure be a value between 0 and 1, which is hard to reflect accurately if your return type is int. That's an exercise left up to you to reconcile. recPower should probably return a double type if the input parameter is a double.

Upvotes: 1

Eduardo Pascual Aseff
Eduardo Pascual Aseff

Reputation: 1166

As divx commented, the problem is that your funtion doesn't work well with negative expontents: it enters in an infinite recursion (not exactly infinite, but it causes an stack overflow).

Other thing, is that if the base is double or you want to process negative exponents, then the function should return a double.

This will do the work:

double recPower(double a, int b)
{
    if (b < 0)
    {
        return 1.0/recPower(a, -b);
    }
    else if (b == 0)
    {
        return 1;
    }
    return (a *recPower(a, b-1));
}

Output for your example:

POWER
----------
2^-3 = 0.125

Upvotes: 0

Related Questions