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 ; Print the total candies ; Driver Code
< ? php function candies ( $ n , $ k ) { $ count = 0 ; $ ind = 1 ; $ arr = array_fill ( 0 , $ k , 0 ) ; $ low = 0 ; $ high = $ n ; while ( $ low <= $ high ) { $ mid = ( $ low + $ high ) >> 1 ; $ sum = ( $ mid * ( $ mid + 1 ) ) >> 1 ; if ( $ sum <= $ n ) { $ count = ( int ) ( $ mid / $ k ) ; $ low = $ mid + 1 ; } else { $ high = $ mid - 1 ; } } $ last = ( $ count * $ k ) ; $ n -= ( int ) ( ( $ last * ( $ last + 1 ) ) / 2 ) ; $ i = 0 ; $ term = ( $ count * $ k ) + 1 ; while ( $ n ) { 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 ) ) + ( int ) ( $ k * ( $ count * ( $ count - 1 ) ) / 2 ) ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; } $ n = 7 ; $ k = 4 ; candies ( $ n , $ k ) ; ? >