Martijn Luyckx
Martijn Luyckx

Reputation: 410

Why does my recursive function in C cause a stack overflow?

I'm trying to make a function calculating x to the power n (where x could be a double, n must be an int). A recursive algorithm would be this one, but implementing it in C gave me the stack-overflow error.

I tried finding my answer here, but the closest I found was this, which didn't satisfy my needs.

Here is my code:

double power_adapted(double x, int n) {
    if (n == 0)
        return 1;
    else if (n == 1)
        return x;
    else if (n % 2 == 0)
        return power_adapted(power_adapted(x, n / 2), 2);
    else
        return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}

Upvotes: 2

Views: 174

Answers (2)

DBug
DBug

Reputation: 2566

The recursive calls always pass 2 as n, so they will always trigger another recursive call.

I think you misinterpreted the formula. I would interpret it as:

else if (n % 2 == 0) {
    double v = power_adapted(x, n / 2);
    return v * v;
}
else {
    double v = power_adapted(x, (n - 1) / 2);
    return x * (v * v);
}

Upvotes: 5

anon
anon

Reputation:

I don't think what you're trying to accomplish makes sense.

If you take a look at this part of code,

else if (n % 2 == 0)
    return power_adapted(power_adapted(x, n / 2), 2);
else
    return power_adapted(power_adapted(x, (n - 1) / 2), 2);

While the nested calls may present no problem (as a statement), the call on the outside always has n = 2 and the base cases depend on n.

Solving the problem:

By taking a look at the formula provided, I think you should have a base case for n == 2 to return x * x (this is the simplest change to the algorithm). So, the algorithm could be stated as follows:

double power_adapted(double x, int n) {
    if (n == 0)
        return 1;
    else if (n == 1)
        return x;
    else if (n == 2)
        return x * x;
    else if (n % 2 == 0)
        return power_adapted(power_adapted(x, n / 2), 2);
    else
        return x * power_adapted(power_adapted(x, (n - 1) / 2), 2);
}

Upvotes: 3

Related Questions