Distinct powers of a number N such that the sum is equal to K | Java implementation to find distinct powers of N that add upto 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 ; Print - 1 if power is being used twice ; If the power is not visited , then mark the power as visited ; Decrementing the value of K ; Printing the powers of N that sum up to K ; Driver code
class GFG { static int highestPower ( int n , int k ) { int i = 0 ; int a = ( int ) Math . pow ( n , i ) ; while ( a <= k ) { i += 1 ; a = ( int ) Math . pow ( n , i ) ; } return i - 1 ; } static int b [ ] = new int [ 50 ] ; static int PowerArray ( int n , int k ) { while ( k > 0 ) { int t = highestPower ( n , k ) ; if ( b [ t ] > 0 ) { System . out . print ( - 1 ) ; return 0 ; } else b [ t ] = 1 ; k -= Math . pow ( n , t ) ; } for ( int i = 0 ; i < 50 ; i ++ ) { if ( b [ i ] > 0 ) { System . out . print ( i + " , ▁ " ) ; } } return 0 ; } public static void main ( String [ ] args ) { int N = 3 ; int K = 40 ; PowerArray ( N , K ) ; } }