On 2 October 2016 at 13:46, Andrei Alexandrescu via Digitalmars-d <[email protected]> wrote: > On 10/01/2016 11:05 PM, Manu via Digitalmars-d wrote: >> >> Unsigned case is: >> return (x & -x) > (x - 1); >> >> Wouldn't this be better: >> return (sz & (sz-1)) == 0; >> >> I also don't understand the integer promotion and recursive call in >> the integer case. Can someone explain how the std.math implementation >> is ideal? > > > The intent is to return 0 when the input is 0. Looking at > https://github.com/dlang/phobos/blob/master/std/math.d, the implementation > for signed integers might be simplified a bit. -- Andrei
Yeah, I feel that's probably sub-optimal, but I haven't tried to solve with that case in mind. I have a feeling that if you have to handle x == 0, then it might be possible to make the signed and unsigned cases identical... it smells like there's a '>' in there in that case, which should be able to eliminate negative cases aswell as the 0 case. I'm not sure this is written in a way where, if you're able to convince the optimiser that x > 0, that the optimiser is able to eliminate the unnecessary work. It's pretty easy to convince the optimiser of valid value ranges, and in the case you demonstrate x > 0, it should empower the optimiser to produce the most efficient version.
