This is a Python program to find whether a number is a power of two.
A number is given. The problem is to determine whether the number is a power of two.
1. The function is_power_of_two is defined.
2. It takes a number n as argument and returns True if the number is a power of two.
3. If n is not positive, False is returned.
4. If n is positive, then n & (n – 1) is calculated.
5. The above expression equals n with its rightmost set bit cleared. That is, the rightmost 1 in the binary representation of n is made 0.
6. All powers of two have only one set bit in their binary representation and all numbers with only one set bit is a power of two.
7. Thus n & (n – 1) will equal zero iff n is a power of two.
8. This is used to determine if n is a power of two if n is positive.
Here is the source code of a Python program to find whether a number is a power of two. The program output is shown below.
def is_power_of_two(n): """Return True if n is a power of two.""" if n <= 0: return False else: return n & (n - 1) == 0 n = int(input('Enter a number: ')) if is_power_of_two(n): print('{} is a power of two.'.format(n)) else: print('{} is not a power of two.'.format(n))
1. The user is prompted to enter a number.
2. is_power_of_two is called on the number.
3. If the return value is True, the number is a power of two.
Case 1: Enter a number: 5 5 is not a power of two. Case 2: Enter a number: 0 0 is not a power of two. Case 3: Enter a number: 8 8 is a power of two.
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Apply for Python Internship
- Practice Programming MCQs
- Check Information Technology Books
- Apply for Programming Internship
- Check Python Books