how to get the thighest bit position in big integers?

Mark Dickinson dickinsm at gmail.com
Wed Oct 8 04:56:34 EDT 2008


On Oct 7, 5:19 pm, mmgar... at gmx.de wrote:
> but I want to make clear that I think that (0).numbits()==-1
> is the natural solution. At least for all square-and-multiply-like
> algorithms needed in [...]

Can you clarify this?  Why is -1 the natural solution? I
can see a case for 0, for -infinity (whatever that means),
or for raising an exception, but I can't see why -1 would
be at all useful or natural.

Here's a straightforward (mildly inefficient)
implementation of the left-to-right square-and-multiply algorithm
for powering.  It works just fine with nbits(0) == 0.

def nbits(n):
    return 0 if n == 0 else len(bin(abs(n)))-2

def LtoRpow(a, n):
    acc = 1
    for i in reversed(xrange(nbits(n))):
        acc *= acc
        if n & (1<<i):
            acc *= a
    return acc




More information about the Python-list mailing list