Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active April 5, 2016 16:49
Show Gist options
  • Select an option

  • Save mmloveaa/0c3d279dfa5bc50b395329d931ce5683 to your computer and use it in GitHub Desktop.

Select an option

Save mmloveaa/0c3d279dfa5bc50b395329d931ce5683 to your computer and use it in GitHub Desktop.
4-5
Complete the given function growth that will calculate how many years until a town reaches a given population. The population will begin at a given start population. At the end of each year, the population will grow by a given percent, and then the population will change by a constant value called aug (inhabitants coming or leaving each year). Calculate how many years until it reaches the given goal population.
Note: Population should always be an integer, so always remove any decimal portion after each year. (Always round down)
Input Format:
The function will have 4 arguments
start - the initial population
percent - the percentage of population growth each year. (ex: 2 represents 2% growth)
aug - the constant number of inhabitants coming or leaving each year
goal - the population to meet or exceed
Remember to convert the percent parameter to a decimal value so you can use it. (If the percent is 5, you should convert it to 0.05)
Output Format:
The function will return the number of years after which the goal has been met. This number should be an integer.
Sample Input 1:
start: 1000, percent: 2, aug: 50, goal: 1200
Sample Output 1:
3
Explanation 1:
At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants
At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)
At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213
It will need 3 entire years.
Sample Input 2:
start: 100, percent: 10, aug: -5, goal: 200
Sample Output 2:
13
Explanation 2:
The population begins at 100 before the first year. At the end of each year, the population grows by 10%, and then 5 people leave. After 13 years, the population is at least 200.
function growth(pop, percent, aug, goal) {
var years = 0 ;
percent /= 100;
while(pop < goal) {
pop += Math.floor(pop * percent) + aug;
years++;
}
return years
}
growth(1000,2,50,1200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment