Checking if an Integer is an Exact Binary Power
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Sun Apr 24 08:33:09 PDT 2016
On 04/24/2016 02:57 AM, deadalnix wrote:
> On Saturday, 23 April 2016 at 15:29:08 UTC, Andrei Alexandrescu wrote:
>> Yah, that's the canonical. I forgot why I chose (x & -x) > (x - 1)
>> over it.
>
> I'm not sure why do you test against x - 1 when you could test for
> equality. Not only it looks like it is going to require an extra
> computation (x - 1) but also it doesn't work for 0.
So if you do (x & -x) == x that returns 1 for x == 0. For many
applications you want to yield 0. So you test for (x & -x) > (x - 1)
such that for x == 0 the right hand side is a large number. -- Andrei
More information about the Digitalmars-d
mailing list