计算二项式系数和使用 Apache Math 包

This commit is contained in:
Yucheng Hu 2018-12-29 19:36:53 -05:00
parent dd15b81b3a
commit c3d2a81f36
2 changed files with 288 additions and 252 deletions

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ossez</groupId>

View File

@ -1,8 +1,10 @@
package com.ossez.codebank.interview.tests;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.util.CombinatoricsUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -74,4 +76,39 @@ public class WayfairTest {
}
/**
* https://www.cwiki.us/display/ITCLASSIFICATION/Binomial+Coefficient
*
* Binomial Coefficient
*/
@Test
public void testBinomialCoefficient() {
int n = 40;
int k = 20;
BigDecimal bc = factorial(n).divide(factorial(k).multiply(factorial(n - k)));
// a.compareTo(new BigDecimal(1000000000))
logger.debug("{}", bc);
logger.debug("Check for Compare To - [{}]", bc.compareTo(new BigDecimal(1000000000)));
logger.debug("Value - [{}]", bc);
logger.debug("Apache CombinatoricsUtils Factorial - [{}]", CombinatoricsUtils.factorialDouble(20));
logger.debug("Apache CombinatoricsUtils Binomial Coefficient - [{}]", CombinatoricsUtils.binomialCoefficientDouble(40, 20));
}
/**
* for factorial
*
* @param x
* @return
*/
private static BigDecimal factorial(int x) {
if (x == 1 || x == 0) {
return BigDecimal.valueOf(1);
} else {
return BigDecimal.valueOf(x).multiply(factorial(x - 1));
}
}
}