Skip to content

Instantly share code, notes, and snippets.

@florabtw
Created February 7, 2014 05:35
Show Gist options
  • Save florabtw/8857799 to your computer and use it in GitHub Desktop.
Save florabtw/8857799 to your computer and use it in GitHub Desktop.
Iterative derangements / subfactorials using BigDecimals and BigIntegers in Java
public BigInteger derangement(int num) {
if (num == 0) {
return BigInteger.ONE;
}
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i <= num; i++) {
BigDecimal fact = new BigDecimal(factorial(i));
BigDecimal toAdd = BigDecimal.valueOf(Math.pow(-1, i)).divide(fact, MathContext.DECIMAL128);
sum = sum.add(toAdd);
}
BigDecimal answer = new BigDecimal(factorial(num)).multiply(sum, MathContext.DECIMAL128);
return answer.toBigInteger();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment