I'm trying to implement a recursive power function in C++, but it fails with large n due to stack overflow. Here's the code:
class Solution {
public:
double myPow(double x, int n) {
long long exp = n;
if (exp < 0) {
x = 1 / x;
exp = -exp;
}
return pow(x, exp);
}
double pow(double x, long long n) {
if (n == 0) return 1;
return x * pow(x, n - 1); // Recursive call
}
};
It works fine for small values of n, but when I run it for large values like
myPow(2.0, 1000000000)
, I get a stack overflow error.
What I Want to Know:
Why is this recursive code causing a stack overflow?
What's the best way to optimize this implementation?
Should I use iteration or a different recursion pattern?
What I’ve Tried:
I tried using long long to avoid integer overflow.
I suspect too many recursive calls might be the issue.
myPow(2.0, 1000000000)would require 1 billion stack frames? Do you understand what your code is going to do withmyPow(2.0, -1)?