Check if given number is a power of d where d is a power of 2 | Python3 program to find if a number is power of d where d is power of 2. ; Function to count the number of ways to paint N * 3 grid based on given conditions ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is a multiple of log2 ( d ) then return true else false ; If there are more than 1 bit set then n is not a power of 4 ; Driver Code
def Log2n ( n ) : NEW_LINE INDENT return ( 1 + Log2n ( n / 2 ) ) if ( n > 1 ) else 0 ; NEW_LINE DEDENT def isPowerOfd ( n , d ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( n and ( n & ( n - 1 ) ) == 0 ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT n >>= 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT return ( count % ( Log2n ( d ) ) == 0 ) ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT n = 64 ; NEW_LINE d = 8 ; NEW_LINE if ( isPowerOfd ( n , d ) ) : NEW_LINE INDENT print ( n , " is ▁ a ▁ power ▁ of " , d ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , " is ▁ not ▁ a ▁ power ▁ of " , d ) ; NEW_LINE DEDENT