Python Program to Check if a Number Is Power of 2

1. Introduction

Identifying whether a number is a power of two is a common problem in computer science, particularly because binary systems are based on powers of two. This task can be done efficiently using bitwise operations in Python.

A number is a power of two if it can be expressed as 2 raised to the power of n, where n is a non-negative integer. For example, 1, 2, 4, 8, and 16 are all powers of two.

2. Program Steps

1. Accept or define a number to check.

2. Check if the number is less than or equal to zero, which cannot be a power of two.

3. Use a bitwise operation to check if the number is a power of two.

4. Print the result.

3. Code Program

# Function to check if a number is a power of two
def is_power_of_two(number):
    # A power of two in binary has a single '1' bit and all other bits as '0'
    # Using 'number & (number - 1)' will clear the lowest set bit and should result in zero for powers of two
    return number > 0 and (number & (number - 1)) == 0

# Number to check
num_to_check = 16
# Check and print the result
if is_power_of_two(num_to_check):
    print(f"{num_to_check} is a power of two.")
else:
    print(f"{num_to_check} is not a power of two.")

Output:

16 is a power of two.

Explanation:

1. is_power_of_two is a function that takes an integer number.

2. It first checks if number is greater than 0, as negative numbers and zero cannot be powers of two.

3. It then performs a bitwise AND operation between number and number - 1. If the result is 0, the number is a power of two, as powers of two have only one bit set in binary representation.

4. num_to_check is set to 16, and the function is_power_of_two is called to determine if it is a power of two.

5. The output of the program confirms that 16 is indeed a power of two, matching the condition described in step 3.

Comments