- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements