Distinct powers of a number N such that the sum is equal to K | Initializing the PowerArray with all 0 's ; Function to find the powers of N that add up to K ; Initializing the counter ; Executing the while loop until K is greater than 0 ; If K % N == 1 , then the power array is incremented by 1 ; Checking if any power is occurred more than once ; For any other value , the sum of powers cannot be added up to K ; Printing the powers of N that sum up to K ; Driver code
let b = new Array ( 50 ) ; b . fill ( 0 ) ; function PowerArray ( n , k ) { let count = 0 ; while ( k > 0 ) { if ( k % n == 0 ) { k = parseInt ( k / n , 10 ) ; count ++ ; } else if ( k % n == 1 ) { k -= 1 ; b [ count ] ++ ; if ( b [ count ] > 1 ) { document . write ( - 1 ) ; return 0 ; } } else { document . write ( - 1 ) ; return 0 ; } } for ( let i = 0 ; i < 50 ; i ++ ) { if ( b [ i ] != 0 ) { document . write ( i + " " ) ; } } return Number . MIN_VALUE ; } let N = 3 ; let K = 40 ; PowerArray ( N , K ) ;