Find k numbers which are powers of 2 and have sum N | Set 1 | function to prnumbers ; Count the number of set bits ; Not - possible condition ; Stores the number ; Get the set bits ; Iterate till we get K elements ; Get the topmost element ; append the elements / 2 into priority queue ; Prall elements ; Driver Code
def printNum ( n , k ) : NEW_LINE INDENT x = 0 NEW_LINE m = n NEW_LINE while ( m ) : NEW_LINE INDENT x += m & 1 NEW_LINE m >>= 1 NEW_LINE DEDENT if k < x or k > n : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT pq = [ ] NEW_LINE two = 1 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT pq . append ( two ) NEW_LINE DEDENT two = two * 2 NEW_LINE n = n >> 1 NEW_LINE DEDENT while ( len ( pq ) < k ) : NEW_LINE INDENT el = pq [ - 1 ] NEW_LINE pq . pop ( ) NEW_LINE pq . append ( el // 2 ) NEW_LINE pq . append ( el // 2 ) NEW_LINE DEDENT ind = 0 NEW_LINE pq . sort ( ) NEW_LINE while ( ind < k ) : NEW_LINE INDENT print ( pq [ - 1 ] , end = " ▁ " ) NEW_LINE pq . pop ( ) NEW_LINE ind += 1 NEW_LINE DEDENT DEDENT n = 9 NEW_LINE k = 4 NEW_LINE printNum ( n , k ) NEW_LINE