Distribute N candies among K people | C # implementation of the above approach ; 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
using System ; class GFG { static void candies ( int n , int k ) { int count = 0 ; int ind = 1 ; int [ ] arr = new int [ k ] ; for ( int i = 0 ; i < k ; i ++ ) arr [ i ] = 0 ; int low = 0 , high = n ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; int sum = ( mid * ( mid + 1 ) ) >> 1 ; if ( sum <= n ) { count = mid / k ; low = mid + 1 ; } else { high = mid - 1 ; } } int last = ( count * k ) ; n -= ( last * ( last + 1 ) ) / 2 ; int j = 0 ; int term = ( count * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ j ++ ] = term ; n -= term ; term ++ ; } else { arr [ j ] += n ; n = 0 ; } } for ( int i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( int i = 0 ; i < k ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int n = 7 , k = 4 ; candies ( n , k ) ; } }