Power of 2 Checker

Check whether a positive integer is a power of 2 using a loop.

PythonBeginner
Python
# Program to check if a number is a power of 2

n = int(input("Enter a positive integer: "))

if n <= 0:
    print("Please enter a positive integer.")
else:
    while n % 2 == 0:
        n //= 2
    if n == 1:
        print("It is a power of 2")
    else:
        print("It is not a power of 2")

Output

Enter a positive integer: 16
It is a power of 2

We divide by 2 until the number is no longer even; if we eventually get 1, the original number was a power of 2.