zoukankan      html  css  js  c++  java
  • 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;
    }


  • 相关阅读:
    Scrum Meeting 11.11
    Scrum Meeting 11.10
    Scrum Meeting 11.09
    Scrum Meeting 11.08
    Scrum Meeting 11.07
    Scrum Meeting 11.06
    Scrum Meeting 11.05
    Scrum Meeting 11.04
    团队博客-应用功能说明书
    Scrum Meeting 11.03
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564011.html
Copyright © 2011-2022 走看看