Distinct powers of a number N such that the sum is equal to K | Java implementation to find out the powers of N that add upto 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
class GFG { static int b [ ] = new int [ 50 ] ; static int PowerArray ( int n , int k ) { int count = 0 ; while ( k > 0 ) { if ( k % n == 0 ) { k /= n ; count ++ ; } else if ( k % n == 1 ) { k -= 1 ; b [ count ] ++ ; if ( b [ count ] > 1 ) { System . out . print ( - 1 ) ; return 0 ; } } else { System . out . print ( - 1 ) ; return 0 ; } } for ( int i = 0 ; i < 50 ; i ++ ) { if ( b [ i ] != 0 ) { System . out . print ( i + " , ▁ " ) ; } } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { int N = 3 ; int K = 40 ; PowerArray ( N , K ) ; } }