Code Chef problem COOKMACH
is it good practice (as per optimization) to write separate loops.


That depends on the logic you need to implement. For example, if you have two loops iterating over the same range and having the same body, then it would be good to combine them to eliminate the code duplication. But that's not the case here, as the two loops can have distinct ranges. By combining the loops, you extend the range, and evaluate some condition more than necessary. 

Take for example the input 256 and target 1. There's no need to evaluate the first condition more than once. After one check, it's enough to evaluate the second condition repeatedly until you reach the target number.

It's very often not possible to separate the conditions like this, effectively serializing the operations. For example if you have an unordered collection of users and you want to filter out those under age 20 and above 60, you have no choice but iterate over the entire collection, and to avoid two loops with identical bodies, it will be good to combine the conditions. You cannot just iterate while users are under 20 and then continue while users are above 60, since the collection is not known to be ordered that way. If it was, you would benefit from splitting the loop, reducing the number of evaluated conditions.

By the way, a funny thing about the challenge in question is that you could even flip the order of those two loops, for example this will work too:

while(a&gt;b){
        a&gt;&gt;=1;
        count++;
}
while(a&amp;(a-1)){ 
        a&gt;&gt;=1;
        count++;
}


The point is,
in this example the loops don't operate on the same range.
They each reduce the range,
and they can do that independently to get the same result.

Code review

Keep in mind that using namespace std is considered bad practice. A practical alternative:

using std::cin;
using std::cout;


Some other minor improvements:


It's better to declare variables where you use them, in the smallest scope
The code would be more readable if you put spaces around operators
The indentation is inconsistent
It's recommended to have one statement per line
No need for return 0 at the end of the main method, the compiler adds it automatically


Like this:

#include &lt;iostream&gt;

using std::cin;
using std::cout;

int main() {
    int testCases;
    cin &gt;&gt; testCases;
    while (testCases--) {
        unsigned long int a, b;
        cin &gt;&gt; a &gt;&gt; b;

        int count = 0;
        while (a &amp; (a - 1)) { 
            a &gt;&gt;= 1;
            count++;
        }
        while (a &gt; b) {
            a &gt;&gt;= 1;
            count++;
        }
        while (a != b) {
            a &lt;&lt;= 1;
            count++;
        }       

        cout &lt;&lt; count &lt;&lt; "\n";
    }
}