How to sum the digits of N! (N factorial) in C++

2 Answers

0 votes
#include <iostream>
#include <vector>

int sumOfDigitsInFactorial(int N) {
    std::vector<int> result(1, 1); // Initialize with 1 (0! = 1)
    
    for (int i = 2; i <= N; ++i) {
        int carry = 0;
        for (auto &digit : result) {
            int product = digit * i + carry;
            digit = product % 10;
            carry = product / 10;
        }
        while (carry) {
            result.push_back(carry % 10);
            carry /= 10;
        }
    }
    
    int sum = 0;
    for (int digit : result) {
        sum += digit;
    }
    
    return sum;
}

int main() {
    int N = 10; // 10! = 3628800 = 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27

    std::cout << "The sum of the digits in " << N << "! is " << sumOfDigitsInFactorial(N) << "\n";
}

   
    
/*
run:
   
The sum of the digits in 10! is 27
 
*/

 



answered Aug 6, 2025 by avibootz
edited Aug 6, 2025 by avibootz
0 votes
#include <iostream>
#include <vector>

long factorial(long n) {
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}

int sumDigits(long num) {
    int sum = 0;
    
    while (num != 0) {
        sum += num % 10;
        num /= 10;
    }
    
    return sum;
}

int main() {
    int N = 10; // 10! = 3628800 = 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
    
    std::cout << "The sum of the digits in " << N << "! is " << sumDigits(factorial(N)) << "\n";
}

   
    
/*
run:
   
The sum of the digits in 10! is 27
 
*/

 



answered Aug 6, 2025 by avibootz

Related questions

1 answer 175 views
1 answer 169 views
1 answer 214 views
1 answer 194 views
1 answer 196 views
1 answer 207 views
...