I use the following function to calculate log base 2 for integers:
public static int log2(int n){
if(n <= 0) throw new IllegalArgumentException();
Try Math.log(x) / Math.log(2)
Why not:
public static double log2(int n)
{
return (Math.log(n) / Math.log(2));
}
Some cases just worked when I used Math.log10:
public static double log2(int n)
{
return (Math.log10(n) / Math.log10(2));
}
let's add:
int[] fastLogs;
private void populateFastLogs(int length) {
fastLogs = new int[length + 1];
int counter = 0;
int log = 0;
int num = 1;
fastLogs[0] = 0;
for (int i = 1; i < fastLogs.length; i++) {
counter++;
fastLogs[i] = log;
if (counter == num) {
log++;
num *= 2;
counter = 0;
}
}
}
Source: https://github.com/pochuan/cs166/blob/master/ps1/rmq/SparseTableRMQ.java