Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find largest power of two less than X number?

Tags:

python

find

I m doing this

def power_two(n, base = -1):
    result = 2 ** base
    if result < n:
        base += 1
        power_two(n, base)
    else:
        if result == n:
            print base
        else:
            print base - 1

what is the pythonic way to find largest power of two less than X number?

EDIT example: power_two(100) return only the power

like image 953
user422100 Avatar asked Sep 26 '10 11:09

user422100


People also ask

How do you find the largest power of 2 less than the given number?

Given a number n, find the highest power of 2 that is smaller than or equal to n. A simple solution is to start checking from n and keep decrementing until we find a power of 2.

How do you find the highest power of 2?

Example 2: Maximum power of 2 in 48! => [482]+[4822]+[4823]+[4824]+[4825]+[4826]+… [ 48 2 ] + [ 48 2 2 ] + [ 48 2 3 ] + [ 48 2 4 ] + [ 48 2 5 ] + [ 48 2 6 ] + … => [482]+[484]+[488]+[4816]+[4832]+[4864]+…

What is the largest power of 2?

1,180,591,620,717,411,303,424 bytes = 1 zettabyte (or zebibyte). The binary approximation of the yotta-, or 1,000,000,000,000,000,000,000,000 multiplier. 1,208,925,819,614,629,174,706,176 bytes = 1 yottabyte (or yobibyte). 286 is conjectured to be the largest power of two not containing a zero in decimal.


1 Answers

Find the logarithm and truncate it:

def power_two(n):
    return int(math.log(n, 2))
like image 133
Mark Byers Avatar answered Oct 24 '22 07:10

Mark Byers