198,439 views
37 votes
37 votes
Write a recursive function is_pow2(n) that returns True if the positive integer n is an integer power of 2, and False otherwise. For example: function call return value is_pow2(1) True is_pow2(2) True is_pow2(3) False is_pow2(4) True is_pow2(5) False is_pow2(6) False is_pow2(7) False is_pow2(8) True is_pow2(9) False is_pow2(255) False is_pow2(256) True Hint: Consider using repeated floor division.

User Ido Schacham
by
2.3k points

1 Answer

20 votes
20 votes

Answer:

In Python:

def is_power(n):

if n > 2:

n = n/2

return is_power(n)

elif n == 2:

return True

else:

return False

Step-by-step explanation:

This defines the function

def is_power(n):

If n is greater than 0

if n > 2:

Divide n by 2

n = n/2

Call the function

return is_power(n)

If n equals 2

elif n == 2:

Return True

return True

If n is less than 2

else:

Then, return false

return False

User Shatl
by
2.7k points