I have been reading Algorithms, 4th Edition, and it defines a question as follows:
Write a static method
lg()
that takes anint
valueN
as an argument and returns the largestint
not larger than the base-2 logarithm ofN
in Java. Do not use Math.
I discovered the following solution:
public static int lg(int N) {
int x = 0;
for (int n = N; n > 1; n/= 2) x++;
return x;
}
I am wondering why that solution works. Why does dividing by 2 continuously allow us to find the largest integer less than the base 2 logarithm of the argument? I do understand Java, just not how this particular algorithm works.
Thank you.