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
def candies ( n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE ind = 1 ; NEW_LINE arr = [ 0 ] * k ; NEW_LINE low = 0 ; NEW_LINE high = n ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 ; NEW_LINE sum = ( mid * ( mid + 1 ) ) >> 1 ; NEW_LINE if ( sum <= n ) : NEW_LINE INDENT count = int ( mid / k ) ; NEW_LINE low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT DEDENT last = ( count * k ) ; NEW_LINE n -= int ( ( last * ( last + 1 ) ) / 2 ) ; NEW_LINE i = 0 ; NEW_LINE term = ( count * k ) + 1 ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( term <= n ) : NEW_LINE INDENT arr [ i ] = term ; NEW_LINE i += 1 ; NEW_LINE n -= term ; NEW_LINE term += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] += n ; NEW_LINE n = 0 ; NEW_LINE DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT arr [ i ] += ( ( count * ( i + 1 ) ) + int ( k * ( count * ( count - 1 ) ) / 2 ) ) ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT n = 7 ; NEW_LINE k = 4 ; NEW_LINE candies ( n , k ) ; NEW_LINE