Log base 2 of large integers

Dave Angel davea at davea.name
Wed Aug 13 10:10:04 EDT 2014


Mok-Kong Shen <mok-kong.shen at t-online.de> Wrote in message:
> 
> I like to compute log base 2 of a fairly large integer n but
> with math.log(n,2) I got:
> 
> OverflowError: long int too large to convert to float.
> 
> Is there any feasible work-around for that?
> 
> Thanks in advance.
> 
> M. K. Shen
> 

Easiest way to get the integer part is to convert to binary
 string,  and take the length of that string.
Call that m.

Then construct a string consisting of a 1 followed by m zeroes.
 
Convert that to a long,  and divide your original number by it.
 Now take the log base 2 of the quotient. Add that to m and you
 have your answer, plus or minus 1.

-- 
DaveA




More information about the Python-list mailing list