Factorial digit sum | Project Euler | Problem #20
URL to the problem page: https://projecteuler.net/problem=20
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!
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!
#include <iostream>
using namespace std;
int main()
{
const int k = 158;
int number[k] = { 0 }, result[3][k] = { 0 }, carry, carry2, carry3, sum = 0, i, a, multiply[3] = { 0, 0, 2 };
number[k - 1] = 1;
for (a = 1; a < 100; a++) {
carry = carry2 = carry3 = 0;
for (i = k - 1; i >= 0; i--) {
result[2][i] = ((multiply[2] * number[i]) + carry) % 10;
carry = ((multiply[2] * number[i]) + carry) / 10;
result[1][i] = ((multiply[1] * number[i]) + carry2) % 10;
carry2 = ((multiply[1] * number[i]) + carry2) / 10;
result[0][i] = ((multiply[0] * number[i]) + carry3) % 10;
carry3 = ((multiply[0] * number[i]) + carry3) / 10;
}
number[k - 1] = result[2][k - 1];
number[k - 2] = (result[2][k - 2] + result[1][k - 1]) % 10;
carry = (result[2][k - 2] + result[1][k - 1]) / 10;
number[k - 3] = (result[2][k - 3] + result[1][k - 2] + result[0][k - 1] + carry) % 10;
carry = (result[2][k - 3] + result[1][k - 2] + result[0][k - 1] + carry) / 10;
for (i = k - 4; i >= 0; i--) {
number[i] = (result[2][i] + result[1][i + 1] + result[0][i + 2] + carry) % 10;
carry = (result[2][i] + result[1][i + 1] + result[0][i + 2] + carry) / 10;
}
for (int j = 2; j >= 0; j--) {
if (multiply[j] == 9) {
multiply[j] = 0;
}
else if (multiply[j] < 9) {
multiply[j]++;
break;
}
}
}
for (i = 0; i < k; i++) {
sum += number[i];
}
cout << "Sum of the digits in the number 100! is = " << sum << endl;
Comments
Post a Comment