Distinct powers of a number N such that the sum is equal to K | Python 3 implementation to find distinct powers of N that add up 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 ; 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
from math import pow NEW_LINE def highestPower ( n , k ) : NEW_LINE INDENT i = 0 NEW_LINE a = pow ( n , i ) NEW_LINE while ( a <= k ) : NEW_LINE INDENT i += 1 NEW_LINE a = pow ( n , i ) NEW_LINE DEDENT return i - 1 NEW_LINE DEDENT b = [ 0 for i in range ( 50 ) ] NEW_LINE def PowerArray ( n , k ) : NEW_LINE INDENT while ( k ) : NEW_LINE INDENT t = highestPower ( n , k ) NEW_LINE if ( b [ t ] ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return 0 NEW_LINE DEDENT else : NEW_LINE INDENT b [ t ] = 1 NEW_LINE DEDENT k -= pow ( n , t ) NEW_LINE DEDENT for i in range ( 50 ) : NEW_LINE INDENT if ( b [ i ] ) : NEW_LINE INDENT print ( i , end = ' , ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 40 NEW_LINE PowerArray ( N , K ) NEW_LINE DEDENT