Codechef COOKMACH solution, exceeding time limit I'm stuck on Codechef problem COOKMACH, which asks for the minimum number of operations needed to transform integer A into integer B, where each operation can be either doubling the number or halving it (rounding down). 1 ≤ A ≤ 107 and  1 ≤ B ≤ 107, and B is an integer power of 2.

In eclipse, the code runs in time, but when it is run in Codechef, the time limit is exceeded.

Is there anything that can be improved in code below?

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(b.readLine());// no. of test cases
while(T&gt;0){
    StringTokenizer s=new StringTokenizer(b.readLine());
    int count=0;
    int A =Integer.parseInt(s.nextToken());
    int B=Integer.parseInt(s.nextToken());
    if(A%2!=0){
        if(A&lt;B){
            while(A!=1){
                A=(A-1)/2;
                count=A;
            }
            while(A&lt;B){
                A=A*2;
                count++;
            }
        }
        else{
            while(A!=B){
                A=(A-1)/2;
                count++;
            }
        }
    }
    else{
        if(A&lt;B){
            while(A!=B){
                A=A*2;
                count++;
            }
        }
        else{
            while(A!=B){
                A=A/2;
                count++;
            }
        }
    }
    T--;
}
}
}
if(A%2!=0){
        if(A&lt;B){
            while(A!=1){
                A=(A-1)/2;
                count=A;
            }



This looks like a bug.  Consider the case where A is 5 and B is 8 or more.  A is odd, less than B, and not equal to 1, so it enters the while loop.  First iteration A becomes 2.  Second iteration we have \$(2-1)/2\$ which rounds down to become 0.  Since 0 is not equal to 1, we loop again and have \$(0-1)/2\$ which rounds off to 0 (negative fractions rounds up, towards zero).  But now we're back to 0.  So it loops endlessly.  

This is why I would recommend saying A &gt; 1 rather than A != 1.  Then you would have returned an answer (possibly wrong) quickly rather than gotten Time Limit Exceeded.  

The worst part is that this is unnecessary.  Integer arithmetic would have handled this correctly.  You don't need to check for odd numbers.  Normal integer arithmetic already rounds down.  

The count=A; is also wrong.  You'd want to increment count here as well, not set it to 1.  

You also don't correctly handle values for A like 6.  It's not odd, but it's not a power of two either.  You should reduce it to 1, but you won't so long as it is less than B.  Instead you'll endlessly double it until the program crashes.