VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-digits-factorial-number/

⇱ Find sum of digits in factorial of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find sum of digits in factorial of a number

Last Updated : 23 Jul, 2025

Given a number n, write code to find the sum of digits in the factorial of the number. Given n ≤ 5000
Examples:

Input : 10
Output : 27
Input : 100
Output : 648

It is not possible to store a number as large as 100! under some data types so, idea is to store an extremely large number in a vector. 

1) Create a vector to store factorial digits and
 initialize it with 1.
2) One by one multiply numbers from 1 to n to 
 the vector. We use school mathematics for this
 purpose.
3) Sum all the elements in vector and return the sum.

Output
10539

Time complexity: O(n^2) since using multiple loops
Auxiliary space: O(n) because it is using space for vector v

Approach#2: Using for loop

This approach calculates the factorial of the given number using a loop and then finds the sum of its digits by converting the factorial to a string and iterating through each character to add the digit to a running total. 

Algorithm

1. Compute the factorial of the given number using any of the previous approaches.
2. Convert the factorial to a string.
3. Traverse through each character in the string and convert it to an integer and add it to the sum variable.
4. Return the sum.


Output
Sum of digits factorial for n=10: 27
Sum of digits factorial for n=100: 648

Time complexity: O(n)), where n is the given number
Auxiliary Space: O(1)

Comment
Article Tags: