Solution to Project Euler Problem 20: Factorial digit sum - 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!
Updated: Sept. 21, 2023 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Project Euler Problem 20: Factorial digit sum
Difficulty: Easy.
Objective: 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!
Input: None.
Expected Output: 648.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
import java.math.BigInteger;
public class SikademyEulerSolution {
public String run() {
String temp = factorial(100).toString();
int sum = 0;
for (int i = 0; i < temp.length(); i++)
sum += temp.charAt(i) - '0';
return Integer.toString(sum);
}
// Returns n!.
public static BigInteger factorial(int n) {
if (n < 0)
throw new IllegalArgumentException("Factorial of negative number");
BigInteger prod = BigInteger.ONE;
for (int i = 2; i <= n; i++)
prod = prod.multiply(BigInteger.valueOf(i));
return prod;
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
import math
# We do a straightforward computation thanks to Python's built-in arbitrary precision integer type.
def compute():
n = math.factorial(100)
ans = sum(int(c) for c in str(n))
return str(ans)
if __name__ == "__main__":
print(compute())