Python Program to Find Whether a Number is a Power of Two

This is a Python program to find whether a number is a power of two.

Problem Description

A number is given. The problem is to determine whether the number is a power of two.

Problem Solution

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.

Program/Source Code

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))
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.