Best way to get ceil(log2(x)) of a BigInt?

pineapple via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 2 07:49:08 PDT 2016


On Wednesday, 2 November 2016 at 14:24:42 UTC, Andrea Fontana 
wrote:
> On Wednesday, 2 November 2016 at 14:05:50 UTC, pineapple wrote:
>> I'm trying to do some math stuff with std.bigint and realized 
>> there's no obvious way to calculate the ceil of log2 of a 
>> bigint. Help?
>
> How big are your bigints?

I think they'll generally stay between 0 and 2^200

I came up with this, I guess it'll work?

    auto clog2(BigInt number) in{
         assert(number > 0);
     }body{
         uint log;
         auto n = number - 1;
         while(n > 0){
             log++; n >>= 1;
         }
         return log;
     }


More information about the Digitalmars-d-learn mailing list