Minimum size of set having either element in range [ 0 , X ] or an odd power of 2 with sum N | Function to find the highest odd power of 2 in the range [ 0 , N ] ; If P is even , subtract 1 ; Function to find the minimum operations to make N ; If N is odd and X = 0 , then no valid set exist ; Stores the minimum possible size of the valid set ; Loop to subtract highest odd power of 2 while X < N , step 2 ; If N > 0 , then increment the value of answer by 1 ; Return the resultant size of set ; Driver Code
function highestPowerof2 ( n ) { let p = Math . floor ( Math . log2 ( n ) ) ; if ( p % 2 == 0 ) { p -= 1 } return Math . pow ( 2 , p ) } function minStep ( N , X ) { if ( N % 2 != 0 && X == 0 ) return - 1 let size = 0 while ( X < N ) { N -= highestPowerof2 ( N ) size += 1 } if ( N != 0 ) size += 1 return size ; } let N = 11 let X = 2 document . write ( minStep ( N , X ) )