Java examples for java.lang:Math Calculation
Calculates the multinomial coefficient.
/******************************************************************************* * Copyright 2014 Felipe Takiyama/* www .j a v a 2 s . c o m*/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main{ /** * Calculates the * <a href="https://en.wikipedia.org/wiki/Multinomial_coefficient# * Multinomial_coefficients">multinomial coefficient.</a> * * @param m The multinomial to calculate * @return The value of the specified multinomial */ public static BigInteger multinomial(Multinomial m) { BigInteger result = BigInteger.ONE; if (m.size() < 2 || m.isZeroed()) { result = BigInteger.ONE; } else { for (int i = 1; i < m.size(); i++) { int n = m.sumTerms(0, i); int k = m.get(i); BigInteger c = combination(n, k); result = result.multiply(c); } } return result; } /** * Calculates the binomial coefficient C(n,k). * <br> * This method returns 0 if n = 0 and k > 0. It throws an * IllegalArgumentException if any specified argument is negative. * * @param n A nonnegative integer * @param k A nonnegative integer * @return The binomial coefficient C(n,k). * @throws IllegalArgumentException If the specified arguments are * negative (at least one of them) */ public static BigInteger combination(int n, int k) throws IllegalArgumentException { if (n < 0 || k < 0) { throw new IllegalArgumentException( "Cannot calculate combination" + " for negative numbers."); } if (n == 0) { return BigInteger.ZERO; } BigInteger r = BigInteger.ONE; int nMinusK = n - k; for (int i = 1; i <= k; i++) { r = r.multiply(BigInteger.valueOf(nMinusK + i)).divide( BigInteger.valueOf(i)); } return r; } }