Find sum of digits in factorial of a number in C++


Suppose, we have a number n, our task is to find the sum of digits in then!. Consider n = 5, then n! = 120. So the result will be 3.

To solve this problem, we will create a vector to store factorial digits and initialize it with 1. Then multiply 1 to n one by one to the vector. Now sum all the elements in the vector and return the sum

Example

 Live Demo

#include<iostream>
#include<vector>
using namespace std;
void vectorMultiply(vector<int> &v, int x) {
   int carry = 0, res;
   int size = v.size();
   for (int i = 0 ; i < size ; i++) {
      int res = carry + v[i] * x;
      v[i] = res % 10;
      carry = res / 10;
   }
   while (carry != 0) {
      v.push_back(carry % 10);
      carry /= 10;
   }
}
int digitSumOfFact(int n) {
   vector<int> v;
   v.push_back(1);
   for (int i=1; i<=n; i++)
      vectorMultiply(v, i);
   int sum = 0;
   int size = v.size();
   for (int i = 0 ; i < size ; i++)
      sum += v[i];
   return sum;
}
int main() {
   int n = 40;
   cout << "Number of digits in " << n << "! is: " << digitSumOfFact(n);
}

Output

Number of digits in 40! is: 189

Updated on: 19-Dec-2019

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements