Smallest number greater than n that can be represented as a sum of distinct power of k | Function to find the smallest number greater than or equal to n represented as the sum of distinct powers of k ; Vector P to store the base k representation of the number ; If the representation is >= 2 , then this power of k has to be added once again and then increase the next power of k and make the current power 0 ; Reduce all the lower power of k to 0 ; Check if the most significant bit also satisfy the above conditions ; Converting back from the k - nary representation to decimal form . ; Driver code
function greaterK ( n , k ) { let p = new Array ( String ( n ) . length + 2 ) . fill ( 0 ) ; let index = 0 ; let x = n ; while ( x > 0 ) { p [ index ] = ( x % k ) ; x = Math . floor ( x / k ) ; index ++ ; } let idx = 0 ; for ( let i = 0 ; i < p . length - 1 ; ++ i ) { if ( p [ i ] >= 2 ) { p [ i ] = 0 ; p [ i + 1 ] ++ ; for ( let j = idx ; j < i ; ++ j ) { p [ j ] = 0 ; } idx = i + 1 ; } if ( p [ i ] == k ) { p [ i ] = 0 ; p [ i + 1 ] ++ ; } } let j = p . length - 1 ; if ( p [ j ] >= 2 ) { p [ index ] = 1 ; index ++ ; } let ans = 0 ; for ( let i = p . length - 1 ; i >= 0 ; -- i ) { ans = ans * k + p [ i ] ; } document . write ( ans + " " ) ; } let n = 29 , k = 7 ; greaterK ( n , k ) ;