Skip to content

Question 29

The function is_power_of_two(n) will return True if n is a power of 2 (i.e., n = 2**k for some k). Otherwise, it returns False. For example,

print(is_power_of_two(1024)) # will print True
print(is_power_of_two(1026)) # will print False

Complete the code below by filling in the blank. Your code must be recursive and not use loop structures or list comprehension. [5 marks]

1
2
3
4
def is_power_of_two(n):
    if n == 1:
        return True
    return ___BLANK_1___
Model Solution
1
2
3
4
def is_power_of_two(n):
if n == 1:
    return True
return n % 2 == 0 and is_power_of_two(n//2)
  • Blank 1: n % 2 == 0 and is_power_of_two(n//2)