Generate an array of size K which satisfies the given conditions | Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code
function generateArray ( n , k ) { var array = Array ( k ) . fill ( 0 ) ; var remaining = n - parseInt ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) document . write ( " " ) ; var right_most = remaining % k ; var high = parseInt ( Math . ceil ( remaining / ( k * 1.0 ) ) ) ; var low = parseInt ( Math . floor ( remaining / ( k * 1.0 ) ) ) ; for ( i = k - right_most ; i < k ; i ++ ) array [ i ] = high ; for ( i = 0 ; i < ( k - right_most ) ; i ++ ) array [ i ] = low ; for ( i = 0 ; i < k ; i ++ ) array [ i ] += i + 1 ; if ( k - 1 != remaining k == 1 ) { for ( var u = 0 ; u < array . length ; u ++ ) document . write ( array [ u ] + " " ) ; } else if ( k == 2 k == 3 ) document . write ( " " ) ; else { array [ 1 ] -= 1 ; array [ k - 1 ] += 1 ; for ( var f = 0 ; f < array . length ; f ++ ) document . write ( array [ f ] + " " ) ; } } var n = 26 , k = 6 ; generateArray ( n , k ) ;