Project Euler: Problem 20 – Factorial digit sum

Problem 20:

n! means n x (n – 1) x … x 3 x 2 x 1
 
For example, 10! = 10 x 9 x … x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
 
Find the sum of the digits in the number 100!

Idea:

Another problem made trivial by the BigInteger class. Seriously, that class is awesome for these problems.

int answer = 0;

BigInteger fact100 = BigInteger.valueOf(100);
for(int i = 99; i > 1; i--) {
   fact100 = fact100.multiply(BigInteger.valueOf(i));
}

String number = fact100.toString();
for(int i = 0; i < number.length(); i++) {
   int tmp = Integer.parseInt(""+number.charAt(i));
   answer+=tmp;
}

System.out.println("Answer: "+answer);
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *