
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if given number is a power of d where d is a power of 2 in Python
Suppose we a number n and another value x, we have to check whether it is a power of x or not, where x is a number power of 2.
So, if the input is like n = 32768 x = 32, then the output will be True as n is x^3.
To solve this, we will follow these steps −
- From the main method do the following −
- cnt := 0
- if n is not 0 and (n AND (n - 1)) is same as 0, then
- while n > 1, do
- n = n/2
- cnt := cnt + 1
- return cnt mod (log c base 2) is same as 0
- while n > 1, do
- return False
Example
Let us see the following implementation to get better understanding −
def find_pow_of_2(n): return (1 + find_pow_of_2(n / 2)) if (n > 1) else 0 def solve(n, c): cnt = 0 if n and (n & (n - 1)) == 0: while n > 1: n >>= 1 cnt += 1 return cnt % (find_pow_of_2(c)) == 0 return False n = 32768 x = 32 print(solve(n, x))
Input
32768, 32
Output
True
- Related Articles
- How to check if a number is a power of 2 in C#?
- JavaScript program to check whether a given number is power of 2
- Check if a number is a power of another number in C++
- Check if a number is power of 8 or not in C++
- Program to check a number is power of two or not in Python
- The power of a lens is, −2 D. What is its focal length?
- Check if a number is power of k using base changing methods in C++
- If work is done at a faster rate, then (a) power is more (b) No power is required to do work (c) power is less (d) Infinite power is required
- Check if n is divisible by power of 2 without using arithmetic operators in Python
- Golang Program to check the power of 4 of a given number
- Check if bitwise AND of any subset is power of two in Python
- Checking if a number is a valid power of 4 in JavaScript
- Number of pairs whose sum is a power of 2 in C++
- What is the nature of a lens whose power is, −4 D?
- What is the nature of a lens having a power of + 0.5 D?

Advertisements