Last active
December 20, 2015 00:48
-
-
Save rfaisal/6043981 to your computer and use it in GitHub Desktop.
Find the sum of the digits in the number 100!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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))); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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