Distribute N candies among K people | Python3 code for better approach to distribute candies ; 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
import math as mt NEW_LINE def candies ( n , k ) : NEW_LINE INDENT count = 0 NEW_LINE ind = 1 NEW_LINE arr = [ 0 for i in range ( k ) ] NEW_LINE while n > 0 : NEW_LINE INDENT f1 = ( ind - 1 ) * k NEW_LINE f2 = ind * k NEW_LINE sum1 = ( f1 * ( f1 + 1 ) ) // 2 NEW_LINE sum2 = ( f2 * ( f2 + 1 ) ) // 2 NEW_LINE res = sum2 - sum1 NEW_LINE if ( res <= n ) : NEW_LINE INDENT count += 1 NEW_LINE n -= res NEW_LINE ind += 1 NEW_LINE i = 0 NEW_LINE term = ( ( ind - 1 ) * k ) + 1 NEW_LINE while ( n > 0 ) : 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 i += 1 NEW_LINE n = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT arr [ i ] += ( ( count * ( i + 1 ) ) + ( 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 , k = 10 , 3 NEW_LINE candies ( n , k ) NEW_LINE