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 ; Last term of last and current series ; Sum of current and last series ; Sum of current series only ; If sum of current is less than N ; } else Individually distribute ; First term ; Distribute candies till there ; Candies available ; Not available ; Count the total candies ; Print the total candies ; Driver Code
function candies ( n , k ) { var count = 0 ; var ind = 1 ; var arr = Array ( k ) ; for ( i = 0 ; i < k ; i ++ ) arr [ i ] = 0 ; while ( n > 0 ) { var f1 = ( ind - 1 ) * k ; var f2 = ind * k ; var sum1 = ( f1 * ( f1 + 1 ) ) / 2 ; var sum2 = ( f2 * ( f2 + 1 ) ) / 2 ; var res = sum2 - sum1 ; if ( res <= n ) { count ++ ; n -= res ; ind ++ ; { var i = 0 ; var term = ( ( ind - 1 ) * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ i ++ ] = term ; n -= term ; term ++ ; } else { arr [ i ++ ] = 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 = 10 , k = 3 ; candies ( n , k ) ;