Find K positive integers not exceeding N and having sum S | Function to represent S as the sum of K positive letegers less than or equal to N ; If S can cannot be represented as sum of K letegers ; If sum of first i natural numbers exceeds S ; Insert i leto nums [ ] ; Insert first K - 1 positive numbers leto 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 ; Prleting the K numbers ; Driver Code
function solve ( S , K , N ) { if ( K > N ) { document . write ( " " ) ; return ; } let max_sum = 0 , min_sum = 0 ; for ( let i = 1 ; i <= K ; i ++ ) { min_sum += i ; max_sum += N - i + 1 ; } if ( S < min_sum S > max_sum ) { document . write ( " " ) ; return ; } let s1 = 0 ; let nums = [ ] ; for ( let i = 1 ; i <= N ; i ++ ) { if ( s1 > S ) break ; s1 += i ; nums . push ( i ) ; } let answer = [ ] ; let s2 = 0 ; for ( let i = 0 ; i < K - 1 ; i ++ ) { answer . push ( nums [ i ] ) ; s2 += nums [ i ] ; } answer . push ( S - s2 ) ; let Max = N ; for ( let i = answer . length - 1 ; i >= 0 ; i -- ) { if ( answer [ i ] > Max ) { let extra = answer [ i ] - Max ; if ( i - 1 >= 0 ) answer [ i - 1 ] += extra ; answer [ i ] = Max ; Max -- ; } else break ; } for ( let x in answer ) document . write ( answer [ x ] + " " ) ; document . write ( " " ) ; } let S = 15 , K = 4 , N = 8 ; solve ( S , K , N ) ;