# 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. log_{2} N in Java.

**Examples:**

Input:N = 2Output:1Input:1024Output: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
log

_{a}b = log_{10}b / log_{10}a - Therefore we can calculate log
_{2}N indirectly as:**log**_{2}N = log_{10}N / log_{10}2Below is the implementation of the above approach:

`// 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

Attention reader! Don’t stop learning now. Get hold of all the important

**Java Foundation**and Collections concepts with the**Fundamentals of Java and Java Collections Course**at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer**Complete Interview Preparation Course****.**