Factorial digit sum (without BigInteger) - 我的博客 - ITeye技术网站
Read full article from Factorial digit sum (without BigInteger) - 我的博客 - ITeye技术网站
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!
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!
- public static int sumFactorialDigits(int n) {
- int sum = 0, carry = 0;
- int[] digits = new int[1000];
- digits[0] = 1;
- digits[1] = 1;
- for (int k = 2; k < n + 1; k++) {
- for (int i = 1; i <= digits[0]; i++) {
- digits[i] = digits[i] * k + carry;
- carry = 0;
- if (digits[i] > 9) {
- carry = digits[i] / 10;
- digits[i] %= 10;
- if (i == digits[0])
- digits[0]++;
- }
- }
- }
- for (int i = digits[0]; i >= 1; i--)
- sum += digits[i];
- return sum;
- }
public static void main(String args[])
{
long start_time= System.currentTimeMillis();
BigInteger data= new BigInteger("1");
for(int index=1;index<=100;++index)
data= data.multiply(new BigInteger(index+""));
String str=data.toString();
long sum=0;
for(int index=0;index<=str.length()-1;++index)
sum+=Integer.parseInt(str.substring(index,index+1));
System.out.println("The sum of the digits in the number 100! :"+sum);
System.out.println("Total time taken:"+ ((System.currentTimeMillis()-start_time)/1000)+"sec");
}
http://cupc71.blogspot.com/2015/01/project-euler-factorial-digit-sum.htmlRead full article from Factorial digit sum (without BigInteger) - 我的博客 - ITeye技术网站