Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log2 for BigInteger in Java

Tags:

java

Wondering if there is an API to calculate log_2 directly? Here is my current code, which I transfer log_2(N) to be log_e(N)/log_e(2).

BTW, it seems for normal Java Double type, there is no method to calculate log_2(double_value) directly?

My code in Java,

BigInteger x = BigInteger.valueOf(16);
BigInteger y = BigInteger.valueOf((long)(Math.log(x.longValue()) / Math.log(2)));
System.out.println(y.doubleValue()); // return 4.0 as expected
like image 371
Lin Ma Avatar asked Sep 02 '26 11:09

Lin Ma


1 Answers

This is built in to the BigInteger API. From the Javadoc:

public int bitLength()

Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes (ceil(log2(this < 0 ? -this : this+1))).)

like image 70
Jim Garrison Avatar answered Sep 04 '26 02:09

Jim Garrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!