Finding Binary Logarithm of Given Number in Golang


In mathematics, a logarithm is an inverse operation of exponentiation. The binary logarithm, also known as the base-2 logarithm, is a logarithm with base 2. The binary logarithm of a number x is the exponent to which the base 2 must be raised to get x. In computer science, binary logarithm is used to represent the complexity of algorithms and data structures.

In this article, we will discuss how to find the binary logarithm of a given number in Golang.

The math package in Golang provides a function called Log2 that can be used to find the binary logarithm of a number. The Log2 function takes a float64 argument and returns its base-2 logarithm as a float64 value.

Here's an example of how to use the Log2 function to find the binary logarithm of a given number −

Example

package main

import (
   "fmt"
   "math"
)

func main() {
   x := 8.0
   binaryLog := math.Log2(x)
   fmt.Printf("Binary logarithm of %v is %v\n", x, binaryLog)
}

Output

Binary logarithm of 8 is 3

The Log2 function can also be used to find the binary logarithm of an integer value by converting it to a float64 value. Here's an example −

Example

package main

import (
   "fmt"
   "math"
)

func main() {
   x := 8
   binaryLog := math.Log2(float64(x))
   fmt.Printf("Binary logarithm of %v is %v\n", x, binaryLog)
}

Output

Binary logarithm of 8 is 3

In case the input value is not a power of 2, we can find the next highest power of 2 using the Ceil function from the math package before calculating its binary logarithm. Here's an example −

Example

package main

import (
   "fmt"
   "math"
)

func main() {
   x := 10
   highPower := math.Ceil(math.Log2(float64(x)))
   binaryLog := highPower - 1
   fmt.Printf("Binary logarithm of %v is %v\n", x, binaryLog)
}

Output

Binary logarithm of 10 is 3

Conclusion

In this article, we learned how to find the binary logarithm of a given number in Golang using the Log2 function from the math package. We also discussed how to handle non-power-of-2 inputs by finding the next highest power of 2 using the Ceil function. The binary logarithm is a powerful mathematical concept that finds its applications in various fields including computer science and engineering.

Updated on: 12-Apr-2023

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements