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
< ? php function candies ( $ n , $ k ) { $ count = 0 ; $ ind = 1 ; $ arr = array_fill ( 0 , $ k , 0 ) ; while ( $ n ) { $ f1 = ( $ ind - 1 ) * $ k ; $ f2 = $ ind * $ k ; $ sum1 = floor ( ( $ f1 * ( $ f1 + 1 ) ) / 2 ) ; $ sum2 = floor ( ( $ f2 * ( $ f2 + 1 ) ) / 2 ) ; $ res = $ sum2 - $ sum1 ; if ( $ res <= $ n ) { $ count ++ ; $ n -= $ res ; $ ind ++ ; } { $ i = 0 ; $ 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 ] += floor ( ( $ count * ( $ i + 1 ) ) + ( $ k * ( $ count * ( $ count - 1 ) ) / 2 ) ) ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) echo $ arr [ $ i ] , " ▁ " ; } $ n = 10 ; $ k = 3 ; candies ( $ n , $ k ) ; ? >