Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda