The challenge description, as it is on Coderbyte:
Have the function PowersofTwo(num) take the num parameter being passed which will be an integer and return the string true if it’s a power of two. If it’s not return the string false. For example if the input is 16 then your program should return the string true but if the input is 22 then the output should be the string false.
Use the Parameter Testing feature in the box below to test your code with different arguments.
One way to check if a number is a power of two is to keep dividing the number by two until the result of the division is one (1). However, when coding this solution, some subtleties need to be considered. Those are explained below.
The starting point of this solution is to check if the number passed is zero (0). If it is zero, the program returns false because 0 is not a power of two.
if num == 0: return "false"
The next step is to divide the given number by two repeatedly. The number is divided until it reaches the value one (1). The most important thing at each iteration is to check the division remainder. Only if there is no remainder, the number is divided by two. Without this condition, the solution will work incorrectly. Thus, if there is no remainder, the number is halved. If there is a remainder, it means the number is not a power of two, and the program returns the words ‘false’. That is done by the code below:
while num > 1: if num % 2 == 0: num = num // 2 else: return "false"
All that is left is to return ‘true’ when the number reaches the value 1 (provided there was no remainder for neither of the divisions beforehand). The full solution can be seen below:
def PowersofTwo(num): if num == 0: return "false" while num > 1: if num % 2 == 0: num = num // 2 else: return "false" return "true"
Coderbyte has two answers. Both can be found at this link. I have tried to make the solution as simple as possible and to avoid any libraries. My solution makes it easier to understand what is happening at each step.