Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that finds how many times n can be divided in half

Tags:

python

Basically, I need a function that will divide n by two and return the number of times it can be done.

Coding so far:

def div(n):
    while n >= 0:
        n / 2
    return n

I know for a fact that I have to use the while loop, but I'm not confident in my third line of coding. What am I doing wrong?

Examples:

>>> div(4)
2
>>> div(7)
2
like image 925
97834657647563 Avatar asked Feb 22 '11 00:02

97834657647563


People also ask

How do you find out how many times a number can be divided by 2?

Any number can be divided by two an infinite number of times. 32 / 2 = 16.

How do you find out how many times a number goes into another number?

Divide - traditional method (long division) The division of two numbers is the process of calculating the number of times one number is contained in another.

Can every number be divided by 2?

Therefore, a number is divisible by 2 if it has a 0, 2, 4, 6, or 8 in the ones place. For example, 54 and 2,870 are divisible by 2, but 2,221 is not divisible by 2.

How many times a number is divisible by 5?

A number is divisible by 5 if the number's last digit is either 0 or 5. Divisibility by 5 - examples: The numbers 105, 275, 315, 420, 945, 760 can be divided by 5 evenly.


2 Answers

An integer n can be divided by 2: floor(log(n)/log(2)) times.

like image 98
Eelvex Avatar answered Oct 20 '22 22:10

Eelvex


/ does not perform assignment. Since you're returning n and not changing its value, I'd think you should start there. Your other hints are = and %.

like image 21
Thomas Dignan Avatar answered Oct 20 '22 21:10

Thomas Dignan