Python program to find the number of required bits to represent a number in O(1) complexity

Here, we will figure out how to locate the number of expected bits to speak to a number in O(1) unpredictability utilizing python?

Issue articulation:

Discover complete Number of bits required to speak to a number in twofold

Example 1:

    input : 10
    output: 4

Example 2:

    input  : 32
    output : 6

Example 1:

    Bits_required = floor(log2(number) + 1)

CODE:

# From math module import log2 and floor function
from math import log2,floor


# Define a function for finding number of bits
# required to represent any number
def countBits(Num) :

    bits = floor(log2(Num) + 1)

    return bits

if __name__ == "__main__" :

    # assign number
    Num = 10

    # function call
    print(countBits(Num))

    Num = 32

    print(countBits(Num))

Output:

4
6

Leave a Comment

error: Alert: Content is protected!!