Factorial digit sum (without BigInteger)

 

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!

From: https://projecteuler.net/problem=20

Solution:

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;
}

 

 

Reference:

http://stackoverflow.com/questions/19334939/factorial-digit-sum-without-bigint-c

你可能感兴趣的:(SUM,factorial,digit)