Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Function to print the required N - th subset ; Nearest power of 2 <= N ; Now insert k ^ p in the answer ; update n ; Print the ans in sorted order ; Driver code
function printSubset ( n , k ) { var answer = [ ] ; while ( n > 0 ) { var p = parseInt ( Math . log2 ( n ) ) ; answer . push ( Math . pow ( k , p ) ) ; n %= parseInt ( Math . pow ( 2 , p ) ) ; } answer . sort ( ) ; for ( var i = 0 ; i < answer . length ; i ++ ) { document . write ( answer [ i ] + " " ) ; } } var n = 5 ; var k = 4 ; printSubset ( n , k ) ;