Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active December 20, 2015 00:48
Show Gist options
  • Select an option

  • Save rfaisal/6043981 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/6043981 to your computer and use it in GitHub Desktop.
Find the sum of the digits in the number 100!
import java.math.BigInteger;
public class FactorialDigitSum {
public FactorialDigitSum() {
}
public static int calculate(int n){
return digitSum(factorial(new BigInteger(""+n))).intValue();
}
private static BigInteger digitSum(BigInteger n){
if(n.compareTo(BigInteger.TEN)==-1) return n;
else return n.mod(BigInteger.TEN).add(digitSum(n.divide(BigInteger.TEN)));
}
private static BigInteger factorial(BigInteger n){
if(n.equals(BigInteger.ONE)) return BigInteger.ONE;
else return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
}
public class FactorialDigitSumTest {
@Test
public void testCalculate() {
assertEquals(1,FactorialDigitSum.calculate(1));
assertEquals(27,FactorialDigitSum.calculate(10));
assertEquals(648,FactorialDigitSum.calculate(100));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment