Lin Ma
Lin Ma

Reputation: 10149

log2 for BigInteger in 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

Upvotes: 2

Views: 2485

Answers (2)

Stuart Schechter
Stuart Schechter

Reputation: 583

If you want partial bits:

const twoToThe50th = Math.pow(2, 50);
const log2BigInt = (x: bigint) => {
  let log = 0;
  while (x > twoToThe50th) {
    // Shift by 6 bytes to right to stay on byte boundaries
    x = x >> BigInt(48);
    log += 48;
  }
  // x is now small enough to be a Number, which we
  // can pass to JavaScript's built in log2 function
  return log + Math.log2(Number(x));
}

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

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))).)

Upvotes: 9

Related Questions