Count ways to distribute m items among n people | Java code for calculating number of ways to distribute m mangoes amongst n people where all mangoes and people are identical ; function used to generate binomial coefficient time complexity O ( m ) ; helper function for generating no of ways to distribute m mangoes amongst n people ; not enough mangoes to be distributed ; ways -> ( n + m - 1 ) C ( n - 1 ) ; Driver function ; m represents number of mangoes n represents number of people
import java . util . * ; class GFG { public static int binomial_coefficient ( int n , int m ) { int res = 1 ; if ( m > n - m ) m = n - m ; for ( int i = 0 ; i < m ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } public static int calculate_ways ( int m , int n ) { if ( m < n ) { return 0 ; } int ways = binomial_coefficient ( n + m - 1 , n - 1 ) ; return ways ; } public static void main ( String [ ] args ) { int m = 7 , n = 5 ; int result = calculate_ways ( m , n ) ; System . out . println ( Integer . toString ( result ) ) ; System . exit ( 0 ) ; } }