26.5k views
0 votes
Write a recursive function next_pow2(n) that returns the smallest integer value p such that for a non-negative value n. For example: function call return value next_pow2(0) 0 next_pow2(1) 0 next_pow2(2) 1 next_pow2(3) 2 next_pow2(4) 2 next_pow2(5) 3 next_pow2(6) 3 next_pow2(7) 3 next_pow2(8) 3 next_pow2(9) 4 next_pow2(255) 8 next_pow2(256) 8 next_pow2(257) 9

1 Answer

2 votes

Answer:

Step-by-step explanation:

The following code is written in Python and is a recursive function as requested that uses the current value of p (which is count in this instance) and raises 2 to the power of p. If the result is greater than or equal to the value of n then it returns the value of p (count) otherwise it raises it by 1 and calls the function again.

def next_pow2(n, count = 0):

if (2**count) < n:

count += 1

return next_pow2(n, count)

else:

return count

Write a recursive function next_pow2(n) that returns the smallest integer value p-example-1
User Johnny Woo
by
3.7k points