Project Euler #20: Factorial digit sum

Sort by

recency

|

111 Discussions

|

  • + 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()
    
  • + 0 comments

    //c # using System; using System; using System.Collections.Generic; using System.IO; class Solution { static void Main(String[] args) { var t = Convert.ToInt32(Console.ReadLine()); for(int i=0; i= 0; i--) sum+=number[i]; Console.WriteLine(sum); } static int Multiply(int times, int[] number,int numLength) { int carry = 0; for (int i = 0; i < numLength; i++) { int product = number[i] * times + carry; number[i] = product % 10; carry = product / 10; }

        while (carry != 0)
        {
            number[numLength] = carry % 10;
            carry /= 10;
            numLength++;
        }
        return numLength;
    }
    

    }