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

133
Vistas
How To Keep Track of The Number of Times a Recursive Function is Called

I'm trying to use recursion to solve the following problem:

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover, 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

This is my code:

function nbYear(p0, percent, aug, p) {
      let years = 0;
      function recYears(p0, percent, aug, p) {
        years += 1;
        if (p/p0 <= 1.06 && p/p0 >= 1) {
          return years;
        } else {
          return nbYear(p0 + p0 * (percent/100) + aug, percent, aug, p)
        } 
      }
      return recYears(p0, percent, aug, p);
    }
console.log(nbYear(1500, 5, 100, 5000))    

I used the variable years outside the recursive function, and I increment it inside. But the issue is that the return of recYears() is 1 when it hits the base case while I'm expecting the return value to be 15, I don't know what I'm missing here! I would appreciate your help.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As Pointy said in the comment, instead of calling recYears() I was calling the outer function nbYear().

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