I were solving:
We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive. The program reports the nth day (as an integer) on which the evaporator will be out of use.
My solution with recursion:
if (content > (initialContent / 100) * threshold) {
double postContent = content - (content / 100) * evap_per_day;
iterations++;
return recursiveEvaporator(postContent, evap_per_day, threshold, initialContent, iterations);
}
But then I found more sophisticated solution:
return (int)Math.ceil(Math.log(threshold / 100.0) / Math.log(1.0 - evap_per_day / 100.0));
Could you please explain me how does logarithms work here and why we choose natural logarithm?
First of all you have to obtain a clear image of e
, that is the base of the natural logarithm.
e
- is constant that represents approximation of (1 + 1/n)^n
that we call for when speaking about constant growth
We see that newly appeared "addition" participated in further exponentiation.Roughly speaking: e^x is our income after x, where x is t*r (t-time; r-rate)
Bringing back the subject of your question
ln(threshold)
- is t*r(time * rate)
ln(1 - evap_per_day)
- is a t*r to evoparate 90% !but not initial, again we need ln
because 90% is constantly decreasing and we chould include it into account.
We divide a product of ln(threshold) by ln(1 - evap_per_day) to get know the time.
So the correct solution is: (int)Math.ceil(Math.log(threshold / 100.0) / (ln(1.0 - evap_per_day / 100.0))