How do you calculate log base 2 in Java for integers?

后端 未结 10 2109
情话喂你
情话喂你 2020-11-29 15:12

I use the following function to calculate log base 2 for integers:

public static int log2(int n){
    if(n <= 0) throw new IllegalArgumentException();
            


        
相关标签:
10条回答
  • 2020-11-29 16:13

    Try Math.log(x) / Math.log(2)

    0 讨论(0)
  • 2020-11-29 16:16

    Why not:

    public static double log2(int n)
    {
        return (Math.log(n) / Math.log(2));
    }
    
    0 讨论(0)
  • 2020-11-29 16:17

    Some cases just worked when I used Math.log10:

    public static double log2(int n)
    {
        return (Math.log10(n) / Math.log10(2));
    }
    
    0 讨论(0)
  • 2020-11-29 16:18

    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

    0 讨论(0)
提交回复
热议问题