Calculate log base 2 of a number in Kotlin
This article explores different ways to calculate the log2 of a number in Kotlin.
1. Using ln() function
The idea is to use the ln(n) function to compute the natural logarithm (base e) of the value n and use the logarithmic identity to calculate log2(n). The logarithmic identity is logba = log10(a)/log10(b), therefore, log2n = log10(n)/log10(2). Note the following special cases as per the Kotlin docs:
ln(NaN)isNaNln(n)isNaNwhenn < 0.0ln(+Inf)is+Infln(0.0)is-Inf
Here's the working example:
|
1 2 3 4 5 6 7 8 9 10 11 |
import kotlin.math.ln fun log2(n: Int): Double { return ln(n.toDouble()) / ln(2.0) } fun main() { val n = 10 val log2n = log2(n) println(log2n) } |
Output:
3.3219280948873626
2. Using Integer.numberOfLeadingZeros() function
The Integer.numberOfLeadingZeros() function returns the number of 0-bits preceding the most significant set bit. Then the log2(n) for a number n can be derived using the formula: 31 - Integer.numberOfLeadingZeros(n).
|
1 2 3 4 5 6 7 8 9 10 |
fun log2(n: Int): Int { require(n > 0) { "n ($n) must be positive" } return 31 - Integer.numberOfLeadingZeros(n) } fun main() { val n = 10 val log2n = log2(n) println(log2n) } |
Output:
3
That's all about calculating the log2 of a number in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)