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.
CodePudding user response:
As Pointy said in the comment, instead of calling recYears()
I was calling the outer function nbYear()
.