Project Euler #20: Factorial digit sum

  • + 0 comments

    Java

    import java.io.*;
    import java.util.*;
    import java.math.BigInteger;
    
    public class Solution {
    
        public static BigInteger factorial(int num) {
            BigInteger result = BigInteger.ONE;
            for (int i = 2; i <= num; i++) {
                result = result.multiply(BigInteger.valueOf(i));
            }
            return result;
        }
    
        public static int sumDigit(BigInteger number) {
            int sum = 0;
            String numberStr = number.toString();
            for (char c : numberStr.toCharArray()) {
                sum += Character.getNumericValue(c);
            }
            return sum;
        }
    
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            int testcase = s.nextInt();
            while (testcase-- > 0) {
                int num = s.nextInt();
                BigInteger result = factorial(num);
                int digitSum = sumDigit(result);
                System.out.println(digitSum);
            }
        }
    }