Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #20 - Factorial digit sum

JaykayChoi 2016. 6. 29. 23:30

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!


출처: https://projecteuler.net/problem=19


100! 의 각 자릿수를 더하는 문제입니다.

매우 큰 수이기 때문에 일반적인 곱셈으로는 구할 수 없습니다.



my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main()
{
    vector <int> digits(1000);
    int ret = 0;
 
    digits[0= 1;
 
    int raising = 0, curDigit = 0;
 
    for (int i = 2; i <= 100; i++)
    {
        for (int j = 0; j <= curDigit; j++)
        {
            digits[j] = digits[j] * i + raising;
            raising = 0;
            if (digits[j] > 9)
            {
                raising = digits[j] / 10;
                digits[j] %= 10;
                if (j == curDigit)
                    curDigit++;
            }
        }
    }
 
    for (int i = 0; i <= curDigit; i++)
        ret += digits[i];
 
    cout << ret << endl;
 
    system("pause");
    return 0;
}
cs