Problem 20: Factorial digit sum

*Difficulty: Easy

Problem:

n! means n × (n − 1) × … × 3 × 2 × 1

For example, 10! = 10 × 9 × … × 3 × 2 × 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!

How to solve :

Dealing with big numbers (hundreds number of digits) is tough. But BigInteger in Java will make it easier than ever. By using BigInteger, this problem can be solve in just the matter of minutes.

Solution took 3 ms

Implementation: Java

import java.math.BigInteger;

public class Prob20 {

publicstaticvoidmain(String[] args) {

long cur = System.currentTimeMillis();

BigIntegerbigN = BigInteger.valueOf(1);

for(long i = 2; i <= 100; ++i) {

bigN = bigN.multiply(BigInteger.valueOf(i));

}

int sum = 0;

String s = bigN.toString();

for(int i = 0; i < s.length(); ++i) {

sum += Integer.valueOf(s.charAt(i)+“”);

}

System.out.println(sum);

System.out.println(“Took “ + (System.currentTimeMillis()cur) + ” ms”);

}

}

Advertisements