Project Euler
Problem 20 (Factorial digit sum)
(이경수)
2019. 4. 7. 10:52
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!
In Python:
# Power digit sum
import time
startTime = time.time()
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
strNum = str(factorial(100))
numList = [int(num) for num in strNum]
print(sum(numList))
print(time.time() - startTime, "seconds")
Run time: 0.0001990795135498047 seconds
In Java:
//Euler20 Factorial digit sum
package project_euler11_20;
import java.math.BigInteger;
public class Euler20 {
public static BigInteger factorial(BigInteger n) {
if (n.compareTo(BigInteger.valueOf(1)) == 0) {
return BigInteger.valueOf(1);
} else {
return n.multiply(factorial(n.subtract(BigInteger.valueOf(1))));
}
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int sum = 0;
BigInteger num = factorial(BigInteger.valueOf(100));
String numString = num.toString();
for (int i = 0; i < numString.length(); i++) {
sum += Integer.parseInt(numString.charAt(i) + "");
}
System.out.println(sum);
long endTime = System.currentTimeMillis();
System.out.println((double)(endTime - startTime) / (double)1000 + "seconds");
}
}
Run time: 0.004seconds
Solution: 648