Distribute N candies among K people | Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Do a binary search to find the number whose sum is less than N . ; Get mide ; If sum is below N ; Find number of complete turns ; Right halve ; Left halve ; Last term of last complete series ; Subtract the sum till ; First term of incomplete series ; Count the total candies ; Prvar the total candies ; Driver Code
function candies ( n , k ) { var count = 0 ; var ind = 1 ; var arr = Array ( k ) . fill ( 0 ) ; for ( i = 0 ; i < k ; i ++ ) arr [ i ] = 0 ; var low = 0 , high = n ; while ( low <= high ) { var mid = parseInt ( ( low + high ) / 2 ) ; var sum = parseInt ( ( mid * ( mid + 1 ) ) / 2 ) ; if ( sum <= n ) { count = parseInt ( mid / k ) ; low = mid + 1 ; } else { high = mid - 1 ; } } var last = ( count * k ) ; n -= ( last * ( last + 1 ) ) / 2 ; var j = 0 ; var term = ( count * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ j ++ ] = term ; n -= term ; term ++ ; } else { arr [ j ] += n ; n = 0 ; } } for ( i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( i = 0 ; i < k ; i ++ ) document . write ( arr [ i ] + " " ) ; } var n = 7 , k = 4 ; candies ( n , k ) ;