Find K positive integers not exceeding N and having sum S | Function to represent S as the sum of K positive integers less than or equal to N ; If S can cannot be represented as sum of K integers ; If sum of first i natural numbers exceeds S ; Insert i into nums [ ] ; Insert first K - 1 positive numbers into answer [ ] ; Insert the K - th number ; Traverse the array answer [ ] ; If current element exceeds N ; Add the extra value to the previous element ; Reduce current element to N ; Printing the K numbers ; Driver Code
def solve ( S , K , N ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT max_sum , min_sum = 0 , 0 NEW_LINE for i in range ( K + 1 ) : NEW_LINE INDENT min_sum += i NEW_LINE max_sum += N - i + 1 NEW_LINE DEDENT if ( S < min_sum or S > max_sum ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT s1 = 0 NEW_LINE nums = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( s1 > S ) : NEW_LINE INDENT break NEW_LINE DEDENT s1 += i NEW_LINE nums . append ( i ) NEW_LINE DEDENT answer = [ ] NEW_LINE s2 = 0 NEW_LINE for i in range ( K - 1 ) : NEW_LINE INDENT answer . append ( nums [ i ] ) NEW_LINE s2 += nums [ i ] NEW_LINE DEDENT answer . append ( S - s2 ) NEW_LINE Max = N NEW_LINE for i in range ( len ( answer ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( answer [ i ] > Max ) : NEW_LINE INDENT extra = answer [ i ] - Max NEW_LINE if ( i - 1 >= 0 ) : NEW_LINE INDENT answer [ i - 1 ] += extra NEW_LINE DEDENT answer [ i ] = Max NEW_LINE Max -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for x in answer : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , K , N = 15 , 4 , 8 NEW_LINE solve ( S , K , N ) NEW_LINE DEDENT