Java examples for java.lang:Math Function
Built in test case for the binomial coefficient function.
//package com.java2s; import java.math.BigInteger; public class Main { public static final BigInteger ZERO = new BigInteger("0", 10); public static final BigInteger ONE = new BigInteger("1", 10); /**//from www .j av a 2s. c om * Built in test case for the binomial coefficient function. */ private static void testBinomialCoefficient() { if (!binomialCoefficient(new BigInteger("64", 10), new BigInteger("32", 10)).equals( new BigInteger("1832624140942590534", 10))) throw new IllegalStateException(); } /** * Computes the binomial coefficient (number of unique ways to choose k elements from a set of n elements) over BigIntegers. * @param n number of elements in the set * @param k number of elements to choose from the set * @return number of ways to choose k elements from n elements in the set */ public static BigInteger binomialCoefficient(BigInteger n, BigInteger k) { BigInteger result = ONE; if (k.compareTo(n) > 0) return ZERO; for (BigInteger i = ONE; i.compareTo(k) < 1; i = i.add(ONE)) { result = result.multiply(n); //result *= n--; n = n.subtract(ONE); result = result.divide(i); //result /= i; } return result; } /** * Computes the binomial coefficient (number of unique ways to choose k elements from a set of n elements). * @param n number of elements in the set * @param k number of elements to choose from the set * @return number of ways to choose k elements from n elements in the set */ public static long binomialCoefficient(long n, long k) { long result = 1; if (k > n) return 0; for (long i = 1; i <= k; i++) { result *= n--; result /= i; } return result; } }