How often can x divided by 2

96 Views Asked by At

I have a question, is there an operation, that can tell me instantly how often x can be divided by 2 (without a reminder).

I mean i can write an easy function:

function howOftenDividedByTwo(x)
{
    var c = 0;
    while(x%2==0)
    {
        c++;
        x/=2;
    }
    return c;
}

howOftenDividedByTwo(10) -> gives 1
howOftenDividedByTwo(20) -> gives 2
howOftenDividedByTwo(32) -> gives 5

And yes, there are some computer science hacks to get the answer, like shifting bits etc.

But i was looking for a mathematical way to describe this (to calculate this).

If this shouldn't be faster possible, can someone represent me this function as mathematical equation, that would be awesome too :)