Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Java program for above approach ; 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 function
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void printSubset ( long n , int k ) { ArrayList < Long > answer = new ArrayList < > ( ) ; while ( n > 0 ) { long p = ( long ) ( Math . log ( n ) / Math . log ( 2 ) ) ; ; answer . add ( ( long ) ( Math . pow ( k , p ) ) ) ; n %= ( int ) Math . pow ( 2 , p ) ; } Collections . sort ( answer ) ; for ( Long x : answer ) { System . out . print ( x + " ▁ " ) ; } } public static void main ( String [ ] args ) { long n = 5 ; int k = 4 ; printSubset ( n , k ) ; } }