Project Euler #20: Factorial digit sum

Sort by

recency

|

112 Discussions

|

  • + 0 comments

    Haskell

    import Control.Applicative
    import Control.Monad
    import System.IO
    import Data.Char
    
    fact :: Integer -> Integer
    fact 0 = 1
    fact 1 = 1
    fact n = n * fact (n-1)
    
    main :: IO ()
    main = do
        t_temp <- getLine
        let t = read t_temp :: Int
        forM_ [1..t] $ \a0  -> do
            n_temp <- getLine
            let n = read n_temp :: Integer
            let num = fact n
            let num_string = show num
            let digits = map (\x -> digitToInt x) num_string
            print(sum digits)
    
  • + 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);
            }
        }
    }
    
  • + 0 comments

    Almost a one-liner:

    from math import factorial
    
    for _ in range(int(input())):
        print(sum(int(d) for d in str(factorial(int(input())))))
    
  • + 0 comments

    java

    BigInteger mult = new BigInteger("1");
            BigInteger sum = new BigInteger("0");
            for (int i = 2; i <= num; i++) {
                mult = mult.multiply(new BigInteger(String.valueOf(i)));
            }
            String sMult = String.valueOf(mult);
            for (int i = 0; i < sMult.length(); i++) {
                String arg = String.valueOf(sMult.charAt(i));
                sum = sum.add(new BigInteger(arg));
            }
            System.out.println(sum);
    
  • + 0 comments

    Python

    def factorial(n):
        if n == 0 or n == 1:
            return 1
        else:
            resultado = n * factorial(n - 1)
            return resultado
    
    def run():
        n = int(input())
        f = factorial(n)
        
        fs = str(f)
        s = 0
        for e in fs:
            s += int(e)
        print(s)
        
    for _ in range(int(input())):
        run()