Taking too much time

here i am going with the brute force method for solving it and not able to think of a method to reduce the time.
please help me with it.

every time i am able to solve the question but i am not able to solve to think of a time efficient way this has become a big issue please help me how one can improve in this field?

hi @saurabh66 can you share your approach with me so I can help you in optimizing it?

in my approach it will involve three loops.
first for taking taking all the inputs from 1 to Q.
second for iterating all the numbers between a and b.
third for checking every bit of that number and storing if bit is set bit by taking & operator then and right shifting till the number till all other bits if that number become zero.

in this way we can make the count of all the set bits.

but due to three loops the time complexity becomes too much.

hi @saurabh66 all of this work is necessary, you are thinking in the right direction. Try to code it out and let me know if you face any trouble

ERROR= TIME LIMIT EXCEED
“this happens with me most of the time please tell how to improve on TIME OPTIMIZATION”
the link of the code is below

hi @saurabh66 the TLE is due to a logical error.
image
see this loop. It will get stuck on the same bit if it is zero. You have to do New >> 1 regardless of whether the bit is 0 or 1.

It should be

while (New > 0) {
    if ((New&1) == 1) { //always use paranthesis when using bitwise operators
        count++;
    }
    New = New >> 1; //do the right shift operation AND assign the new value to New, else it will not be updated.
}
1 Like

Oh. thank you so much!!

hi @saurabh66 dont forget to mark your doubt as resolved! :slight_smile: