DEV Community

Discussion on: Daily Challenge #197 - Population Growth

Collapse
 
vidit1999 profile image
Vidit Sarkar

Starting population : p0
Percent : pct
Inhabitants coming or leaving each year : aug
Population to surpass : p

After n years the total population will be :
(p0 + aug/pct) * ( (1 + pct)n ) - aug/pct
where aug is converted from percentage i.e. from 5% to 0.05

So, n >= (log((aug + pct*p) / (aug + pct*p0) ) / log(1+pct))

Here is the C++ solution

int nbYear(long p0,long double pct, long aug, long p){
    pct /= 100;
    return ceil(log((aug+pct*p)/(aug+pct*p0))/log(1+pct));
}

cout << nbYear(1000,2,50,1200) << "\n";
cout << nbYear(1500,5,100,5000) << "\n";
cout << nbYear(1500000,2.5,10000,2000000) << "\n";
cout << nbYear(1500000,0.25,1000,2000000) << "\n";

Output :

3
15
10
94