How to calculate log base 2 of an Integer in Java?
Given an integer N, the task is to calculate its log to the base 2, i.e. log2 N in Java.
Input: N = 2 Output: 1 Input: 1024 Output: 10
- Math class in Java (java.lang.Math) is a library which holds the functions to calculate such values, like sin(), cos(), log() etc. But the log() method in Math class calculates the log to the base e. Hence there is no direct method in Java to calculate log to the base 2.
- But as we know that
loga b = loge b / loge a
- Therefore we can calculate log2 N indirectly as:
log2 N = loge N / loge 2
Below is the implementation of the above approach:
Log 1024 to the base 2 = 10
My Personal Notes arrow_drop_up
Please Login to comment...