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

137
Views
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 answers
Answer question

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 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!