To calculate the logarithm of any base in Java, we thus have to use the following method:
public double logOfBase(int base, int num) { return Math.log(num) / Math.log(base); }
Why does it work?
Let's say we want to find the base 2 logarithm of 32 (method call would be logOfBase(2, 32)), which is 5.
Now if we divide the base e logarithm (ln) of our number (32) by the base e logarithm of our base (2), we get the answer we wanted: