Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
Getting this error message: Maximum call stack size exceeded

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!