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.
Examples:
Input: N = 2 Output: 1 Input: 1024 Output: 10
Approach:
- 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 10. Hence there is no direct method in Java to calculate log to the base 2.
- But as we know that
loga b = log10 a / log10 b
- Therefore we can calculate log2 N indirectly as:
log2 N = log10 N / log10 2Below is the implementation of the above approach:
// Java code to Calculate log base 2 of an integerimportjava.io.*;importjava.lang.*;classGFG {// Function to calculate the// log base 2 of an integerpublicstaticintlog2(intN){// calculate log2 N indirectly// using log() methodintresult = (int)(Math.log(N) / Math.log(2));returnresult;}// Driver codepublicstaticvoidmain(String[] args){intN =1024;System.out.println("Log "+ N+" to the base 2 = "+ log2(N));}}chevron_rightfilter_noneOutput:Log 1024 to the base 2 = 10
Recommended Posts:
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

