Number of ways to divide beads (with.Java)
This is an article that examines the ānumber of ways to divide marblesā problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Letās look at the problem first.
problem
Iām planning to share the beads with my friends.
The beads all look different.
When balls, the number of marbles the mage has, and share, the number of marbles to share among the balls, are given as parameters, complete the solution function that returns the number of all possible cases of selecting the share number of marbles among the balls.
Restrictions
1 ā¤ balls ā¤ 30
1 ā¤ share ā¤ 30
The order in which beads are selected is not taken into account.
share ā¤ balls
Input/Output Example
balls | share | result |
---|---|---|
3 | 2 | 3 |
5 | 3 | 10 |
My solution to the problem
class Solution {
public int solution(int balls, int share) {
double answer = 1;
for(int i = 0; i < share; i++){
answer = answer * (balls - i) / (i+1);
}
return(int)answer;
}
}
Solution explanation
We are efficiently calculating the number of cases by using factorial calculations to find the binomial coefficients.
The result is converted from double to int and returned. If the number becomes very large, you can initialize the answer to 1 and continue accumulating it, exceeding the range of the integer.
Casting to double and later converting back to int may be incorrect.
Calculations on large numbers have the potential for integer overflow.
So for calculations on larger numbers you can consider long or BigInteger.
Points that can be improved
Casting Note: For accuracy in integer calculations, keep the answer as double when calculating it and consider casting if necessary.
Mathematical optimization: Efficiency can be improved by considering mathematical optimization when calculating the number of cases.
Prevent integer overflow: Use long or BigInteger to prevent overflow when calculating the number of cases for large numbers.