In: Computer Science
Write a function log2(x), which gives an integer approximation of the log base 2 of a positive number x, but it does so using recursion. Use a base case where you return 0 if x is 1 or less. In the general case, add 1 to the answer and divide x by 2. (python 3)
Program:
Note: The following program is done in python 3. Match the indentation as program snip before run.
#log2 function
def log2(x):
#if condtion for recursive function
if(x<=1):
#return 0 value as result
return 0
#recursive function log2 calling it self again and again then add
1
return log2(x/2)+1
#input value x from user as integer
x=int(input("Enter a integer value: "))
#calling log2 function as store result in result variable
result=log2(x)
#displying result
print("The integer approximation of the log base 2 of a positive
number x is:",result)
Sample Output: