Check if given number is a power of d where d is a power of 2 | Javascript 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
function Log2n ( n ) { return ( n > 1 ) ? 1 + Log2n ( n / 2 ) : 0 ; } function isPowerOfd ( n , d ) { var count = 0 ; if ( n > 0 && ( n & ( n - 1 ) ) == 0 ) { while ( n > 1 ) { n >>= 1 ; count += 1 ; } return ( count % ( Log2n ( d ) ) == 0 ) ; } return false ; } var n = 64 , d = 8 ; if ( isPowerOfd ( n , d ) ) document . write ( n + " " + d ) ; else document . write ( n + " " + d ) ;