Saturday, 7 December 2024

Day 26 : Python Program to find whether a given number is power of two


 

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

Popular Posts

Categories

100 Python Programs for Beginner (28) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (223) Cybersecurity (24) data management (11) Data Science (127) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (4) PHP (20) Projects (29) Python (923) Python Coding Challenge (318) Python Quiz (4) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses