How to use recursion to divide a number multiple times and keep track of the iterations?

3007 views python

I'm trying to make a function that will half the integer argument until it's under 1. I also want to keep track of how many iterations it took for it to do this. Here is what I have so far, but I am stuck on what to put in the recursive case:

def case(number):
    if number == 1:
       return 1
       return number * 0.50    # not sure how to do this part

So for example, if I had 20 passed as an argument for "case", I want the recursive case/ function to do 20 * 0.50 (or 20/2)= 10, then take 10 * 0.50 = 5, then take 5 * 0.50 ect.. until the number is under 1.

In this example, it would have taken 6 iterations to get below 1 (0.625).

How do you get the recursive case to keep dividing or taking half of the number and for it to print the amount of iterations it took to the console?

Note: I'm aware that while loops would be a lot more suited for this situation, but the project I'm working, recursion will make it easier later.

Thank you for the help!

answered question

2 Answers


def case(number):
    if number <= 1: # base case (exit)
       return 1
       return 1+case(number * 0.50) # recursive case

posted this

def case(number):
   return recursiveFunc(number, 0, 0.5)
def recursiveFunc(number, count, multiplier):
    if(number <= 1):
       return count
    return recursiveFunc(number*multiplier, count+1, multiplier)

posted this

Have an answer?


Please login first before posting an answer.