Friday, January 30, 2026
HomeLanguagesJavaHow to calculate log base 2 of an Integer in Java?

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: 

        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:

Java




// Java code to Calculate log base 2 of an integer
 
import java.io.*;
import java.lang.*;
 
class GFG {
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
 
        // calculate log2 N indirectly
        // using log() method
        int result = (int)(Math.log(N) / Math.log(2));
 
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int N = 1024;
 
        System.out.println("Log " + N + " to the base 2 = " + log2(N));
    }
}


Output: 

Log 1024 to the base 2 = 10

 

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS