Question

I needed to test the fact that

if you start with an integer = 1, and double it log N (to the base 2) times ,you get N

I thought I 'd write some java code for this.. but then,this is what I got

public class Log2NDoubling {
    public static void main(String[] args) {
        int s = 1;
        int  N = 10;        
        double lg2N = log2(N);
        int intlg2N = (int)lg2N;
        for(int i=0;i< intlg2N;i++){
            s *= 2;
        }
        System.out.println("s="+s);
    }

    private static double log2(int x){
        return Math.log10(x)/Math.log10(2);
    }

}

which produced an output

s=8.0

Well this doesn't exactly prove the above statement..is wrong choice of input data the culprit or is it my code?

Was it helpful?

Solution

You need to pick a number that's a power of 2 for N: 4, 8, 16, 32, 64, 128, etc. or you need to do fractional doubling here:

int intlg2N = (int)lg2N;
for(int i=0;i< intlg2N;i++){

Let's work through this. The log2 (10) is 3.3219. But you're rounding to 3.

So you're getting 2 * 2 * 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top