Minimum size of set having either element in range [ 0 , X ] or an odd power of 2 with sum N | Java program for the above approach ; 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
import java . io . * ; class GFG { static int highestPowerof2 ( int n ) { int p = ( int ) Math . floor ( Math . log ( n ) / Math . log ( 2.0 ) ) ; if ( p % 2 == 0 ) p -= 1 ; int result = ( int ) ( Math . pow ( 2 , p ) ) ; return result ; } static int minStep ( int N , int X ) { if ( N % 2 != 0 && X == 0 ) return - 1 ; int size = 0 ; while ( X < N ) { N -= highestPowerof2 ( N ) ; size += 1 ; } if ( N != 0 ) size += 1 ; return size ; } public static void main ( String [ ] args ) { int N = 11 ; int X = 2 ; System . out . println ( minStep ( N , X ) ) ; } }