Check if given number is a power of d where d is a power of 2 in Python

PythonServer Side ProgrammingProgramming

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
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

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
raja
Published on 18-Jan-2021 17:18:48
Advertisements