Determining Number of Iterations in a loop (Java)
The formula stated in this question works for for loops where i is being added to or subtracted from. My question is how can this formula be changed to give the number of iterations in a for loop where i is being divided or multiplied by a value.
@WJS
CodePudding user response:
for(int i = M; i < N; i*=k)
...
The critical point is when we have been through this loop s times, so that i = M ks = N. Take the logarithm of both sides:
log(M) s log(k) = log(N)
s = (log(N)-log(M))/log(k)
Use the floor function for <= and the ceiling function (minus one) for < (which is what WJS did in the linked question). I don't know Java, so I won't attempt to write Java code.
(There might be a problem if you are multiplying an integer counter by a floating-point factor, or something like that, but I will not accept responsibility for such foolishness.)
