-1

I'm trying to solve this leetcode problem. In this problem, I basically need to return the power of x.

But when I run my solution it returns this error message:

RangeError: Maximum call stack size exceeded

My code:

function myPow(base, exponent){
    if(exponent === 0) {
        return 1;
    } else if(exponent < 0){
        return (myPow(base,exponent + 1)/base);
    } else {
        return base * myPow(base,exponent-1);
    }
}

myPow(0.00001, 2147483647) // this test case is failing only I think

Updated code according to Luca Kiebel's suggestion

function myPow(base, exponent){
    if(exponent === 0) {
        return 1;
    } else if(exponent < 0){
        return (myPow(base,exponent + 1)/base);
    } else {
        return base ** myPow(base,exponent-1);
    }
}

Anyone please explain me where I'm making a mistake.

3 Answers3

1

You're calling the function inside itself too many times, making the JS Engine think there's a problem, and killing it before it takes too much CPU/RAM.

Using Math.pow or a simple for loop (Instead of recursion) should fix the problem.

See Browser Javascript Stack size limit for how many times you can call a function inside another one

Juanjo Martinez
  • 679
  • 7
  • 18
0

You are basically getting that error because your function is calling itself multiple times, until a stack limit is reached.

You can try using Math.pow() function to achieve what you are trying to do.

Spider-Man
  • 50
  • 1
  • 7
0

Recursion is not a good choice if you did want to roll your own raise-to-the-power function, but you can do it in a very simple loop

function myPow(x,n){
  var res = 1;
  for(var i=0;i<Math.abs(n);i++)
    res = n<0 ? res/x : res * x
  return res
}

console.log(myPow(2, 10), Math.pow(2,10), 2 ** 10)
console.log(myPow(2, -2), Math.pow(2,-2), 2 ** -2)
//console.log(myPow(0.00001, 2147483647), Math.pow(0.00001,2147483647), 0.00001 ** 2147483647)

But as you can see from the above examples, you're simply reinventing the wheen of Math.pow or the ** operator

Jamiec
  • 133,658
  • 13
  • 134
  • 193