def power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
num = int(input("Enter a number: "))
if power_of_two(num):
print(f"{num} is a power of two.")
else:
print(f"{num} is not a power of two.")
Code Explanation:
1. Function Definition
def power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
Parameters and Purpose:
The function power_of_two checks if the input n is a power of two.
Logic Breakdown:
Check if n > 0:
A power of two must be a positive number (e.g., 1, 2, 4, 8, etc.).
If n <= 0, the function immediately returns False.
Bitwise Operation (n & (n - 1)):
This checks if n is a power of two:
A power of two in binary form has exactly one bit set to 1 (e.g., 1 = 0b1, 2 = 0b10, 4 = 0b100).
Subtracting 1 flips all bits from the first set bit to the right:
If the result is 0, the number is a power of two.
2. User Input
num = int(input("Enter a number: "))
The user is prompted to enter an integer (num).
int(input(...)) converts the input string to an integer.
3. Conditional Check and Output
if power_of_two(num):
print(f"{num} is a power of two.")
else:
print(f"{num} is not a power of two.")
The power_of_two function is called with num as the argument.
Based on the return value:
If True, the program prints that the number is a power of two.
If False, the program prints that it is not a power of two.
#source code --> clcoding.com
0 Comments:
Post a Comment