Checking if an Integer is an Exact Binary Power

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 26 11:04:53 PDT 2016


On Tuesday, 26 April 2016 at 08:12:02 UTC, Dominikus Dittes 
Scherkl wrote:
> On Monday, 25 April 2016 at 22:42:38 UTC, deadalnix wrote:
>> x & -x is the smallest power of 2 that divides x. Basically, 
>> if x = xxxx1000 , x & -x = 00001000 . This is easy to proves 
>> considering -x = ~x + 1 .
>>
>> Now, x >> 1 will be of the form 0xxxx100 . If one of these 
>> digit is one, then (x >> 1) >= (x & -x) . If they are all 
>> zeros, (x >> 1) < (x & -x) which is the case where you have a 
>> power of 2.
>>
>> 0 is a special case, can it can be checked that the function 
>> return false for this specific input.
>>
>> This looks like it is correct.
>
> Yes. Except for the case 0x80000000 (= int.min), because this 
> is negative so NOT smaller than 0x40000000 (= int.min>>>1), 
> which is considered positive.
> So the algorithm doesn't work for signed integers (without 
> extra cast).

You got to explain me how you end up with a negative number by 
multiplying 2 by 2 a bunch of time.



More information about the Digitalmars-d mailing list