Project Euler Problem 20 Factorial digit sum

Factorial digit sum

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!


C++:

#include <iostream>
#include <cstring>

using namespace std;

const int MAXN = 1000;

int result[MAXN+1];

int factorial(int n)
{
    int digits, j;

    memset(result, 0, sizeof(result));

    result[0] = 1;
    digits = 1;
    for(int i=2; i<=n; i++) {
        int carry = 0;

        for(j=0; j<digits; j++)
            result[j] *= i;

        for(j=0; j<=digits || carry; j++) {
            result[j] += carry;
            carry = result[j] / 10;
            result[j] %= 10;
        }
        digits = j;
    }

    return digits;
}

int main()
{
    int n, digits;

    while(cin >> n) {
        digits = factorial(n);
        int sum = 0;
        for(int i=0; i<=digits; i++)
            sum += result[i];
        cout << sum << endl;
    }

    return 0;
}


没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭