Distinct powers of a number N such that the sum is equal to K | Function to return the highest power of N not exceeding K ; Loop to find the highest power less than K ; Initializing the PowerArray with all 0 's. ; Function to print the distinct powers of N that add upto K ; Getting the highest power of n before k ; To check if the power is being used twice or not ; Prlet - 1 if power is being used twice ; If the power is not visited , then mark the power as visited ; Decrementing the value of K ; Prleting the powers of N that sum up to K ; Driver Code
function highestPower ( n , k ) { let i = 0 ; let a = Math . pow ( n , i ) ; while ( a <= k ) { i += 1 ; a = Math . pow ( n , i ) ; } return i - 1 ; } let b = Array . from ( { length : 50 } , ( _ , i ) => 0 ) ; function PowerArray ( n , k ) { while ( k > 0 ) { let t = highestPower ( n , k ) ; if ( b [ t ] > 0 ) { document . write ( - 1 ) ; return 0 ; } else b [ t ] = 1 ; k -= Math . pow ( n , t ) ; } for ( let i = 0 ; i < 50 ; i ++ ) { if ( b [ i ] > 0 ) { document . write ( i + " " ) ; } } return 0 ; } let N = 3 ; let K = 40 ; PowerArray ( N , K ) ;