text: Distinct powers of a number N such that the sum is equal to K | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int highestPower ( int n , int k ) { int i = 0 ; int a = pow ( n , i ) ; while ( a <= k ) { i += 1 ; a = pow ( n , i ) ; } return i - 1 ; } int b [ 50 ] = { 0 } ; int PowerArray ( int n , int k ) { while ( k ) { int t = highestPower ( n , k ) ; if ( b [ t ] ) { cout << -1 ; return 0 ; } else b [ t ] = 1 ; k -= pow ( n , t ) ; } for ( int i = 0 ; i < 50 ; i ++ ) { if ( b [ i ] ) { cout << i << " , ▁ " ; } } } int main ( ) { int N = 3 ; int K = 40 ; PowerArray ( N , K ) ; return 0 ; }